From 365bd2ca83b29b749e3e14e0358b8883e90e1d42 Mon Sep 17 00:00:00 2001 From: Stavros Kois <47820033+stavros-k@users.noreply.github.com> Date: Fri, 6 Dec 2024 17:10:21 +0200 Subject: [PATCH 1/3] Bump lib part1 (#1139) * remove old lib * bump lib --- ix-dev/enterprise/asigra-ds-system/app.yaml | 6 +- .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ .../{base_v2_0_21 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_21 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 0 .../{base_v2_0_21 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_21 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_21 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 0 .../{base_v2_0_21 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 0 .../{base_v2_0_21 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 0 .../{base_v2_0_21 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_21 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_21 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_21 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_21 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 0 .../tests/test_depends.py | 0 .../library/base_v2_1_0}/tests/test_deps.py | 105 ++- .../library/base_v2_1_0}/tests/test_device.py | 0 .../tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 0 .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 0 .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 0 .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_21 => base_v2_1_0}/volumes.py | 0 ix-dev/enterprise/minio/app.yaml | 6 +- .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 2 + .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../environment.py | 5 +- .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 36 + .../tests/test_depends.py | 0 .../tests/test_deps.py | 105 ++- .../library/base_v2_1_0}/tests/test_device.py | 10 + .../tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../tests/test_healthcheck.py | 8 + .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/enterprise/syncthing/app.yaml | 6 +- .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../{base_v2_0_32 => base_v2_1_0}/devices.py | 2 + .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 5 +- .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 36 + .../tests/test_depends.py | 0 .../library/base_v2_1_0}/tests/test_deps.py | 105 ++- .../tests/test_device.py | 10 + .../tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 8 + .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/collabora/app.yaml | 6 +- .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 2 + .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 5 +- .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../tests/test_container.py | 36 + .../tests/test_depends.py | 0 .../library/base_v2_1_0}/tests/test_deps.py | 105 ++- .../tests/test_device.py | 10 + .../tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 8 + .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/diskoverdata/app.yaml | 6 +- .../library/base_v2_0_31/environment.py | 109 --- .../library/base_v2_0_31/tests/test_device.py | 121 ---- .../base_v2_0_31/tests/test_environment.py | 184 ----- .../{base_v2_0_31 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_31 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../{base_v2_0_31 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_31 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_31 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 2 + .../{base_v2_0_31 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 5 +- .../{base_v2_0_31 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../{base_v2_0_31 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_31 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_31 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_31 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_31 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_31 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_31 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../tests/test_container.py | 36 + .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0}/tests/test_device.py | 10 + .../tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 8 + .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_31 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/elastic-search/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/emby/app.yaml | 6 +- .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ .../{base_v2_0_21 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_21 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_21 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_21 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_21 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_21 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_21 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_21 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_21 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_21 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_21 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_21 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_21 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/home-assistant/app.yaml | 6 +- .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ .../{base_v2_0_21 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_21 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_21 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_21 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_21 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_21 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_21 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_21 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_21 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_21 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_21 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_21 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_21 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/ix-app/app.yaml | 6 +- .../templates/library/base_v2_0_34/deps.py | 454 ------------ .../library/base_v2_0_34/tests/test_deps.py | 380 ---------- .../{base_v2_0_34 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_34 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_34 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_34 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_34 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_34 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_34 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_34 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_34 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_34 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_34 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_34 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_34 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_34 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_34 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/minio/app.yaml | 6 +- .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/functions.py | 111 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ .../{base_v2_0_21 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_21 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_21 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_21 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_21 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_21 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_21 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_21 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_21 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_21 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_21 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_21 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_21 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/netdata/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/nextcloud/app.yaml | 6 +- .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/functions.py | 111 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../templates/library/base_v2_0_21/storage.py | 106 --- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_functions.py | 65 -- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../base_v2_0_21/tests/test_volumes.py | 666 ------------------ .../library/base_v2_0_21/validations.py | 203 ------ .../{base_v2_0_21 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_21 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_21 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_21 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_21 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_21 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_21 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_21 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_21 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_21 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_21 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_21 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_21 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/photoprism/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 3 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/pihole/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 42 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/plex/app.yaml | 6 +- .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/functions.py | 111 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../templates/library/base_v2_0_21/storage.py | 106 --- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_functions.py | 65 -- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../base_v2_0_21/tests/test_volumes.py | 666 ------------------ .../library/base_v2_0_21/validations.py | 203 ------ .../{base_v2_0_21 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_21 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_21 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_21 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_21 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_21 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_21 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 42 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_21 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_21 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_21 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_21 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_21 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_21 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_21 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/prometheus/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0}/functions.py | 42 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/storj/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0/functions.py | 149 ++++ .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/syncthing/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0/functions.py | 149 ++++ .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0/storage.py | 116 +++ .../templates/library/base_v2_1_0/sysctls.py | 38 + .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0/tests/test_functions.py | 88 +++ .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../library/base_v2_1_0/tests/test_volumes.py | 666 ++++++++++++++++++ .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 ix-dev/stable/wg-easy/app.yaml | 6 +- .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../{base_v2_0_32 => base_v2_1_0}/__init__.py | 0 .../{base_v2_0_32 => base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../{base_v2_0_32 => base_v2_1_0}/depends.py | 0 .../{base_v2_0_32 => base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../{base_v2_0_32 => base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../{base_v2_0_32 => base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../{base_v2_0_32 => base_v2_1_0}/error.py | 0 .../formatter.py | 0 .../library/base_v2_1_0/functions.py | 149 ++++ .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../{base_v2_0_32 => base_v2_1_0}/labels.py | 0 .../{base_v2_0_32 => base_v2_1_0}/notes.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portal.py | 0 .../{base_v2_0_32 => base_v2_1_0}/portals.py | 0 .../{base_v2_0_32 => base_v2_1_0}/ports.py | 0 .../{base_v2_0_32 => base_v2_1_0}/render.py | 0 .../resources.py | 0 .../{base_v2_0_32 => base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0/storage.py | 116 +++ .../templates/library/base_v2_1_0/sysctls.py | 38 + .../tests/__init__.py | 0 .../tests/test_build_image.py | 0 .../tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../tests/test_formatter.py | 0 .../base_v2_1_0/tests/test_functions.py | 88 +++ .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../tests/test_labels.py | 0 .../tests/test_notes.py | 0 .../tests/test_portal.py | 0 .../tests/test_ports.py | 0 .../tests/test_render.py | 0 .../tests/test_resources.py | 0 .../tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../library/base_v2_1_0/tests/test_volumes.py | 666 ++++++++++++++++++ .../library/base_v2_1_0/validations.py | 234 ++++++ .../volume_mount.py | 0 .../volume_mount_types.py | 0 .../volume_sources.py | 0 .../volume_types.py | 0 .../{base_v2_0_32 => base_v2_1_0}/volumes.py | 0 1229 files changed, 49166 insertions(+), 39025 deletions(-) delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/container.py delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/deps.py delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/devices.py delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/validations.py rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/__init__.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/configs.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/container.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/depends.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_mariadb.py rename ix-dev/{stable/collabora/templates/library/base_v2_0_32/deps.py => enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/device.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/devices.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/dns.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/environment.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/error.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/formatter.py (100%) rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32 => asigra-ds-system/templates/library/base_v2_1_0}/functions.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/healthcheck.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/labels.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/notes.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/portal.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/portals.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/ports.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/render.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/resources.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/restart.py (100%) rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32 => asigra-ds-system/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32 => asigra-ds-system/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_configs.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/tests/test_container.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_depends.py (100%) rename ix-dev/{stable/diskoverdata/templates/library/base_v2_0_31 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/tests/test_deps.py (80%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/tests/test_device.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_dns.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/tests/test_environment.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32 => asigra-ds-system/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/tests/test_healthcheck.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32 => asigra-ds-system/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32 => asigra-ds-system/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename ix-dev/{stable/ix-app/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/templates/library/base_v2_1_0}/validations.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/enterprise/asigra-ds-system/templates/library/{base_v2_0_21 => base_v2_1_0}/volumes.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) rename ix-dev/{stable/diskoverdata/templates/library/base_v2_0_31 => enterprise/minio/templates/library/base_v2_1_0}/container.py (93%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_mariadb.py rename ix-dev/{stable/diskoverdata/templates/library/base_v2_0_31/deps.py => enterprise/minio/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/minio/templates/library/base_v2_1_0}/devices.py (93%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/environment.py (95%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/functions.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/healthcheck.py (95%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_container.py (89%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_deps.py (80%) rename ix-dev/enterprise/{asigra-ds-system/templates/library/base_v2_0_21 => minio/templates/library/base_v2_1_0}/tests/test_device.py (89%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_healthcheck.py (95%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename ix-dev/enterprise/{syncthing/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/validations.py (94%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/enterprise/minio/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/container.py (93%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_mariadb.py rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32/deps.py => syncthing/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/devices.py (93%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/environment.py (95%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/functions.py (100%) rename ix-dev/{stable/diskoverdata/templates/library/base_v2_0_31 => enterprise/syncthing/templates/library/base_v2_1_0}/healthcheck.py (95%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) rename ix-dev/enterprise/{minio/templates/library/base_v2_0_32 => syncthing/templates/library/base_v2_1_0}/tests/test_container.py (89%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/tests/test_deps.py (80%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_device.py (89%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename ix-dev/{stable/diskoverdata/templates/library/base_v2_0_31 => enterprise/syncthing/templates/library/base_v2_1_0}/tests/test_healthcheck.py (95%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename ix-dev/{stable/collabora/templates/library/base_v2_0_32 => enterprise/syncthing/templates/library/base_v2_1_0}/validations.py (94%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/enterprise/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) rename ix-dev/{enterprise/syncthing/templates/library/base_v2_0_32 => stable/collabora/templates/library/base_v2_1_0}/container.py (93%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/collabora/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_mariadb.py rename ix-dev/{enterprise/syncthing/templates/library/base_v2_0_32/deps.py => stable/collabora/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => collabora/templates/library/base_v2_1_0}/devices.py (93%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) rename ix-dev/{enterprise/syncthing/templates/library/base_v2_0_32 => stable/collabora/templates/library/base_v2_1_0}/environment.py (95%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{elastic-search/templates/library/base_v2_0_32 => collabora/templates/library/base_v2_1_0}/functions.py (100%) rename ix-dev/{enterprise/minio/templates/library/base_v2_0_32 => stable/collabora/templates/library/base_v2_1_0}/healthcheck.py (95%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => collabora/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => collabora/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_container.py (89%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) rename ix-dev/{enterprise/syncthing/templates/library/base_v2_0_32 => stable/collabora/templates/library/base_v2_1_0}/tests/test_deps.py (80%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_device.py (89%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) rename ix-dev/{enterprise/minio/templates/library/base_v2_0_32 => stable/collabora/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => collabora/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename ix-dev/{enterprise/syncthing/templates/library/base_v2_0_32 => stable/collabora/templates/library/base_v2_1_0}/tests/test_healthcheck.py (95%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => collabora/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => collabora/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => collabora/templates/library/base_v2_1_0}/validations.py (94%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/collabora/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/environment.py delete mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_device.py delete mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_environment.py rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/configs.py (100%) rename ix-dev/{enterprise/minio/templates/library/base_v2_0_32 => stable/diskoverdata/templates/library/base_v2_1_0}/container.py (93%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/device.py (100%) rename ix-dev/{enterprise/minio/templates/library/base_v2_0_32 => stable/diskoverdata/templates/library/base_v2_1_0}/devices.py (93%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/dns.py (100%) rename ix-dev/{enterprise/asigra-ds-system/templates/library/base_v2_0_21 => stable/diskoverdata/templates/library/base_v2_1_0}/environment.py (95%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{ix-app/templates/library/base_v2_0_34 => diskoverdata/templates/library/base_v2_1_0}/functions.py (100%) rename ix-dev/stable/{collabora/templates/library/base_v2_0_32 => diskoverdata/templates/library/base_v2_1_0}/healthcheck.py (95%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{elastic-search/templates/library/base_v2_0_32 => diskoverdata/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{elastic-search/templates/library/base_v2_0_32 => diskoverdata/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_configs.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_container.py (89%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_deps.py rename ix-dev/{enterprise/minio/templates/library/base_v2_0_32 => stable/diskoverdata/templates/library/base_v2_1_0}/tests/test_device.py (89%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_dns.py (100%) rename ix-dev/{enterprise/asigra-ds-system/templates/library/base_v2_0_21 => stable/diskoverdata/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{elastic-search/templates/library/base_v2_0_32 => diskoverdata/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename ix-dev/stable/{collabora/templates/library/base_v2_0_32 => diskoverdata/templates/library/base_v2_1_0}/tests/test_healthcheck.py (95%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{elastic-search/templates/library/base_v2_0_32 => diskoverdata/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{elastic-search/templates/library/base_v2_0_32 => diskoverdata/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename ix-dev/{enterprise/minio/templates/library/base_v2_0_32 => stable/diskoverdata/templates/library/base_v2_1_0}/validations.py (94%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/diskoverdata/templates/library/{base_v2_0_31 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/container.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{netdata/templates/library/base_v2_0_32 => elastic-search/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{ix-app/templates/library/base_v2_0_34 => elastic-search/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{ix-app/templates/library/base_v2_0_34 => elastic-search/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{ix-app/templates/library/base_v2_0_34 => elastic-search/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{ix-app/templates/library/base_v2_0_34 => elastic-search/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{ix-app/templates/library/base_v2_0_34 => elastic-search/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/elastic-search/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/elastic-search/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/container.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/deps.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/devices.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/environment.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/emby/templates/library/base_v2_0_21/validations.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/container.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{photoprism/templates/library/base_v2_0_32 => emby/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{netdata/templates/library/base_v2_0_32 => emby/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{netdata/templates/library/base_v2_0_32 => emby/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{netdata/templates/library/base_v2_0_32 => emby/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{netdata/templates/library/base_v2_0_32 => emby/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{netdata/templates/library/base_v2_0_32 => emby/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/emby/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/emby/templates/library/{base_v2_0_21 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/container.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/deps.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/devices.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/environment.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_0_21/validations.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/container.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{pihole/templates/library/base_v2_0_32 => home-assistant/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{photoprism/templates/library/base_v2_0_32 => home-assistant/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{photoprism/templates/library/base_v2_0_32 => home-assistant/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{photoprism/templates/library/base_v2_0_32 => home-assistant/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{photoprism/templates/library/base_v2_0_32 => home-assistant/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{photoprism/templates/library/base_v2_0_32 => home-assistant/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/home-assistant/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/home-assistant/templates/library/{base_v2_0_21 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_0_34/deps.py delete mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_deps.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/container.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{prometheus/templates/library/base_v2_0_32 => ix-app/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{pihole/templates/library/base_v2_0_32 => ix-app/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{pihole/templates/library/base_v2_0_32 => ix-app/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{pihole/templates/library/base_v2_0_32 => ix-app/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{pihole/templates/library/base_v2_0_32 => ix-app/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{pihole/templates/library/base_v2_0_32 => ix-app/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/ix-app/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/ix-app/templates/library/{base_v2_0_34 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/container.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/deps.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/devices.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/environment.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/functions.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/minio/templates/library/base_v2_0_21/validations.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/container.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{storj/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{prometheus/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{prometheus/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{prometheus/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{prometheus/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{prometheus/templates/library/base_v2_0_32 => minio/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/minio/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/minio/templates/library/{base_v2_0_21 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/netdata/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/container.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{syncthing/templates/library/base_v2_0_32 => netdata/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{storj/templates/library/base_v2_0_32 => netdata/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{storj/templates/library/base_v2_0_32 => netdata/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{storj/templates/library/base_v2_0_32 => netdata/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{storj/templates/library/base_v2_0_32 => netdata/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{storj/templates/library/base_v2_0_32 => netdata/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/netdata/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/netdata/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/container.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/deps.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/devices.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/environment.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/functions.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/storage.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_functions.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_volumes.py delete mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_0_21/validations.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/container.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{wg-easy/templates/library/base_v2_0_32 => nextcloud/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{syncthing/templates/library/base_v2_0_32 => nextcloud/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{syncthing/templates/library/base_v2_0_32 => nextcloud/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{syncthing/templates/library/base_v2_0_32 => nextcloud/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{syncthing/templates/library/base_v2_0_32 => nextcloud/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{syncthing/templates/library/base_v2_0_32 => nextcloud/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/nextcloud/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/nextcloud/templates/library/{base_v2_0_21 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/container.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{diskoverdata/templates/library/base_v2_0_31 => photoprism/templates/library/base_v2_1_0}/functions.py (99%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{wg-easy/templates/library/base_v2_0_32 => photoprism/templates/library/base_v2_1_0}/storage.py (100%) rename ix-dev/stable/{wg-easy/templates/library/base_v2_0_32 => photoprism/templates/library/base_v2_1_0}/sysctls.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{wg-easy/templates/library/base_v2_0_32 => photoprism/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) rename ix-dev/stable/{wg-easy/templates/library/base_v2_0_32 => photoprism/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename ix-dev/stable/{wg-easy/templates/library/base_v2_0_32 => photoprism/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 ix-dev/stable/photoprism/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/photoprism/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/pihole/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/container.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/{enterprise/asigra-ds-system/templates/library/base_v2_0_21 => stable/pihole/templates/library/base_v2_1_0}/functions.py (63%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{home-assistant/templates/library/base_v2_0_21 => pihole/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/sysctls.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/{enterprise/asigra-ds-system/templates/library/base_v2_0_21 => stable/pihole/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_sysctls.py rename ix-dev/stable/{emby/templates/library/base_v2_0_21 => pihole/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 ix-dev/stable/pihole/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/pihole/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/container.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/deps.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/devices.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/environment.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/functions.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/storage.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_functions.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_volumes.py delete mode 100644 ix-dev/stable/plex/templates/library/base_v2_0_21/validations.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/container.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{emby/templates/library/base_v2_0_21 => plex/templates/library/base_v2_1_0}/functions.py (63%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/restart.py (100%) rename ix-dev/{enterprise/asigra-ds-system/templates/library/base_v2_0_21 => stable/plex/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/sysctls.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{emby/templates/library/base_v2_0_21 => plex/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_sysctls.py rename ix-dev/stable/{home-assistant/templates/library/base_v2_0_21 => plex/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 ix-dev/stable/plex/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/plex/templates/library/{base_v2_0_21 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/container.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) rename ix-dev/stable/{home-assistant/templates/library/base_v2_0_21 => prometheus/templates/library/base_v2_1_0}/functions.py (63%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{minio/templates/library/base_v2_0_21 => prometheus/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/sysctls.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{home-assistant/templates/library/base_v2_0_21 => prometheus/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_sysctls.py rename ix-dev/{enterprise/asigra-ds-system/templates/library/base_v2_0_21 => stable/prometheus/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 ix-dev/stable/prometheus/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/prometheus/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/storj/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/container.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/functions.py create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) rename ix-dev/stable/{emby/templates/library/base_v2_0_21 => storj/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/sysctls.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) rename ix-dev/stable/{minio/templates/library/base_v2_0_21 => storj/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_sysctls.py rename ix-dev/stable/{minio/templates/library/base_v2_0_21 => storj/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 ix-dev/stable/storj/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/storj/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/container.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/functions.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/storage.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/sysctls.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_functions.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_sysctls.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_volumes.py create mode 100644 ix-dev/stable/syncthing/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/syncthing/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/container.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/deps.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/devices.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/environment.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_0_32/validations.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/__init__.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/configs.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/container.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/depends.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/deploy.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_perms.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_redis.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/device.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/devices.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/dns.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/environment.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/error.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/formatter.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/functions.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/healthcheck.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/labels.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/notes.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/portal.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/portals.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/ports.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/render.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/resources.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/restart.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/storage.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/sysctls.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/__init__.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_build_image.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_container.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_device.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_environment.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_formatter.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_functions.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_healthcheck.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_labels.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_notes.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_portal.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_ports.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_render.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_resources.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_sysctls.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_volumes.py create mode 100644 ix-dev/stable/wg-easy/templates/library/base_v2_1_0/validations.py rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_mount_types.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_sources.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/volume_types.py (100%) rename ix-dev/stable/wg-easy/templates/library/{base_v2_0_32 => base_v2_1_0}/volumes.py (100%) diff --git a/ix-dev/enterprise/asigra-ds-system/app.yaml b/ix-dev/enterprise/asigra-ds-system/app.yaml index 0247e36db1..ce47338fac 100644 --- a/ix-dev/enterprise/asigra-ds-system/app.yaml +++ b/ix-dev/enterprise/asigra-ds-system/app.yaml @@ -19,8 +19,8 @@ keywords: - backup - restore - asigra -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -47,4 +47,4 @@ sources: - https://hub.docker.com/r/asigra/ds-system title: Asigra DS-System train: enterprise -version: 1.0.15 +version: 1.0.16 diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/container.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/deps.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/devices.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/healthcheck.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_container.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_deps.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_healthcheck.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/validations.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/__init__.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/__init__.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/configs.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/configs.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/container.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/container.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/container.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/container.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/depends.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/depends.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/deploy.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/deploy.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/deps.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/deps.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/deps.py +++ b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/device.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/device.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/devices.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/devices.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/devices.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/devices.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/dns.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/dns.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/environment.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/environment.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/environment.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/environment.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/error.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/error.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/formatter.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/formatter.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/functions.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/functions.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/healthcheck.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/healthcheck.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/healthcheck.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/healthcheck.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/labels.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/labels.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/notes.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/notes.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/portal.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/portal.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/portals.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/portals.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/ports.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/ports.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/render.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/render.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/resources.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/resources.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/restart.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/restart.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/storage.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/storage.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/sysctls.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/__init__.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/__init__.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_build_image.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_build_image.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_configs.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_configs.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_container.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_container.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_container.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_container.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_depends.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_depends.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_deps.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_deps.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_deps.py +++ b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_device.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_device.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_device.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_device.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_dns.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_dns.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_environment.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_environment.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_environment.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_environment.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_formatter.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_formatter.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_healthcheck.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_healthcheck.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_healthcheck.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_labels.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_labels.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_notes.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_notes.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_portal.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_portal.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_ports.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_ports.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_render.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_render.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_resources.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_resources.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_restart.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_restart.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/validations.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/validations.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/validations.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/validations.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_mount.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_mount.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_mount_types.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_mount_types.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_sources.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_sources.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_types.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volume_types.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volumes.py b/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/volumes.py rename to ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/enterprise/minio/app.yaml b/ix-dev/enterprise/minio/app.yaml index 4f902e948f..87d0f55112 100644 --- a/ix-dev/enterprise/minio/app.yaml +++ b/ix-dev/enterprise/minio/app.yaml @@ -11,8 +11,8 @@ keywords: - minio - cloud - s3 -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -31,4 +31,4 @@ sources: - https://github.com/minio/minio title: MinIO train: enterprise -version: 1.2.0 +version: 1.2.1 diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/__init__.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/__init__.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/configs.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/configs.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/container.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/container.py similarity index 93% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/container.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/container.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/depends.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/depends.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/deploy.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/deploy.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/deps.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/deps.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/deps.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/device.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/device.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/devices.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/devices.py similarity index 93% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/devices.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/devices.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/dns.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/dns.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/environment.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/environment.py similarity index 95% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/environment.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/environment.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/error.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/error.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/formatter.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/formatter.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/functions.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/functions.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/healthcheck.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/healthcheck.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/labels.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/labels.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/notes.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/notes.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/portal.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/portal.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/portals.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/portals.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/ports.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/ports.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/render.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/render.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/resources.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/resources.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/restart.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/restart.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/storage.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/storage.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/sysctls.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_container.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_container.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_deps.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_deps.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_device.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_device.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_device.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_environment.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_environment.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_healthcheck.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/validations.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/validations.py similarity index 94% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/validations.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/validations.py +++ b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_types.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/volumes.py b/ix-dev/enterprise/minio/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/volumes.py rename to ix-dev/enterprise/minio/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/enterprise/syncthing/app.yaml b/ix-dev/enterprise/syncthing/app.yaml index af06f4c570..e2440f523d 100644 --- a/ix-dev/enterprise/syncthing/app.yaml +++ b/ix-dev/enterprise/syncthing/app.yaml @@ -25,8 +25,8 @@ icon: https://media.sys.truenas.net/apps/syncthing/icons/icon.svg keywords: - sync - file-sharing -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -49,4 +49,4 @@ sources: - https://hub.docker.com/r/syncthing/syncthing title: Syncthing train: enterprise -version: 1.1.0 +version: 1.1.1 diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/__init__.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/__init__.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/configs.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/configs.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/container.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/container.py similarity index 93% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/container.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/container.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/depends.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/depends.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/deploy.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/deploy.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/deps.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/deps.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/deps.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/device.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/device.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/devices.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/devices.py similarity index 93% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/devices.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/devices.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/dns.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/dns.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/environment.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/environment.py similarity index 95% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/environment.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/environment.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/error.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/error.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/formatter.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/formatter.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/functions.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/functions.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/healthcheck.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/healthcheck.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/healthcheck.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/labels.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/labels.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/notes.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/notes.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/portal.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/portal.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/portals.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/portals.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/ports.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/ports.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/render.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/render.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/resources.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/resources.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/restart.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/restart.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/storage.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/storage.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/sysctls.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_container.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_container.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_deps.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_deps.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_device.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_device.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_environment.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_environment.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_healthcheck.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_healthcheck.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_healthcheck.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/validations.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/validations.py similarity index 94% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/validations.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/validations.py +++ b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_types.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volumes.py b/ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/volumes.py rename to ix-dev/enterprise/syncthing/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/collabora/app.yaml b/ix-dev/stable/collabora/app.yaml index ca5a874281..7d575e686c 100644 --- a/ix-dev/stable/collabora/app.yaml +++ b/ix-dev/stable/collabora/app.yaml @@ -27,8 +27,8 @@ keywords: - office - documents - productivity -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -53,4 +53,4 @@ sources: - https://hub.docker.com/r/collabora/code title: Collabora train: stable -version: 1.2.1 +version: 1.2.2 diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/container.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/container.py similarity index 93% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/container.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/container.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/deps.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/deps.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/device.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/devices.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/devices.py similarity index 93% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/devices.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/devices.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/environment.py similarity index 95% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/environment.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/environment.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/error.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/healthcheck.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/healthcheck.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/render.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/storage.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/storage.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/sysctls.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/sysctls.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_container.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_container.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_deps.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_deps.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_device.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_device.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_environment.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_environment.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_functions.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_functions.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_healthcheck.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/ix-dev/enterprise/syncthing/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_sysctls.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_sysctls.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_volumes.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_volumes.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/validations.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/validations.py similarity index 94% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/validations.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/validations.py +++ b/ix-dev/stable/collabora/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/collabora/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/collabora/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/diskoverdata/app.yaml b/ix-dev/stable/diskoverdata/app.yaml index 6ccc9a553d..cc596c6740 100644 --- a/ix-dev/stable/diskoverdata/app.yaml +++ b/ix-dev/stable/diskoverdata/app.yaml @@ -23,8 +23,8 @@ keywords: - monitoring - management - discovery -lib_version: 2.0.31 -lib_version_hash: e61b4db536830d207e591fea73037ca3f335da01a7e4073bb37392d1ede15873 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -50,4 +50,4 @@ sources: - https://github.com/linuxserver/docker-diskover title: Diskover Data train: stable -version: 1.4.1 +version: 1.4.2 diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/environment.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_device.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_environment.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/__init__.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/__init__.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/configs.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/configs.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/container.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/container.py similarity index 93% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/container.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/container.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/depends.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/depends.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/deploy.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/deploy.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/device.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/device.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/devices.py similarity index 93% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/devices.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/devices.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/dns.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/dns.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/environment.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/environment.py similarity index 95% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/environment.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/environment.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/error.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/error.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/formatter.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/formatter.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/functions.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/functions.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/healthcheck.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/healthcheck.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/labels.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/labels.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/notes.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/notes.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/portal.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/portal.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/portals.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/portals.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/ports.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/ports.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/render.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/render.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/resources.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/resources.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/restart.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/restart.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/__init__.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/__init__.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_build_image.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_build_image.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_configs.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_configs.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_container.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_container.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_container.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_depends.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_depends.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_device.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/tests/test_device.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_dns.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_dns.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_environment.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_environment.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_environment.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_formatter.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_formatter.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_healthcheck.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/ix-dev/stable/collabora/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_labels.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_labels.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_notes.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_notes.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_portal.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_portal.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_ports.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_ports.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_render.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_render.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_resources.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_resources.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_restart.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/tests/test_restart.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/validations.py similarity index 94% rename from ix-dev/enterprise/minio/templates/library/base_v2_0_32/validations.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/ix-dev/enterprise/minio/templates/library/base_v2_0_32/validations.py +++ b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_mount.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_mount.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_mount_types.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_mount_types.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_sources.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_sources.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_types.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volume_types.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volumes.py b/ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/volumes.py rename to ix-dev/stable/diskoverdata/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/elastic-search/app.yaml b/ix-dev/stable/elastic-search/app.yaml index dda76d26b9..448574c608 100644 --- a/ix-dev/stable/elastic-search/app.yaml +++ b/ix-dev/stable/elastic-search/app.yaml @@ -10,8 +10,8 @@ icon: https://media.sys.truenas.net/apps/elastic-search/icons/icon.svg keywords: - search - elastic -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -29,4 +29,4 @@ sources: - https://www.elastic.co/guide/en/elasticsearch/reference/master/docker.html#docker-configuration-methods title: Elastic Search train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/container.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/container.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/device.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/error.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/render.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/storage.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/storage.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/sysctls.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/sysctls.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_functions.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_functions.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_sysctls.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_sysctls.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_volumes.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_volumes.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/elastic-search/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/elastic-search/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/emby/app.yaml b/ix-dev/stable/emby/app.yaml index 413479181c..e6ac2c0569 100644 --- a/ix-dev/stable/emby/app.yaml +++ b/ix-dev/stable/emby/app.yaml @@ -27,8 +27,8 @@ keywords: - series - tv - streaming -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -49,4 +49,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/emby title: Emby Server train: stable -version: 1.2.3 +version: 1.2.4 diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/container.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/deps.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/devices.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/environment.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/healthcheck.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_container.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_deps.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_device.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_environment.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_healthcheck.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/validations.py b/ix-dev/stable/emby/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/__init__.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/__init__.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/configs.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/configs.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/container.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/depends.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/depends.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/deploy.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/deploy.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/device.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/device.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/dns.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/dns.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/error.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/error.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/formatter.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/formatter.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/labels.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/labels.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/notes.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/notes.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/portal.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/portal.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/portals.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/portals.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/ports.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/ports.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/render.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/render.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/resources.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/resources.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/restart.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/restart.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/__init__.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/__init__.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_build_image.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_build_image.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_configs.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_configs.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_depends.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_depends.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_dns.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_dns.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_formatter.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_formatter.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_labels.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_labels.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_notes.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_notes.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_portal.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_portal.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_ports.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_ports.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_render.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_render.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_resources.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_resources.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_restart.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_restart.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/emby/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/volume_mount.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/volume_mount.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/volume_mount_types.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/volume_mount_types.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/volume_sources.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/volume_sources.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/volume_types.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/volume_types.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/volumes.py b/ix-dev/stable/emby/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/volumes.py rename to ix-dev/stable/emby/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/home-assistant/app.yaml b/ix-dev/stable/home-assistant/app.yaml index 3d6c12f248..1c470d7249 100644 --- a/ix-dev/stable/home-assistant/app.yaml +++ b/ix-dev/stable/home-assistant/app.yaml @@ -20,8 +20,8 @@ icon: https://media.sys.truenas.net/apps/home-assistant/icons/icon.png keywords: - home-automation - assistant -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -45,4 +45,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/home-assistant title: Home Assistant train: stable -version: 1.3.4 +version: 1.3.5 diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/container.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/deps.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/devices.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/environment.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/healthcheck.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_container.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_deps.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_device.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_environment.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_healthcheck.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/validations.py b/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/__init__.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/__init__.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/configs.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/configs.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/container.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/depends.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/depends.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/deploy.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/deploy.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/device.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/device.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/dns.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/dns.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/error.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/error.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/formatter.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/formatter.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/labels.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/labels.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/notes.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/notes.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/portal.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/portal.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/portals.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/portals.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/ports.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/ports.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/render.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/render.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/resources.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/resources.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/restart.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/restart.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/__init__.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/__init__.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_build_image.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_build_image.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_configs.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_configs.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_depends.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_depends.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_dns.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_dns.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_formatter.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_formatter.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_labels.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_labels.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_notes.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_notes.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_portal.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_portal.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_ports.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_ports.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_render.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_render.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_resources.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_resources.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_restart.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_restart.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_mount.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_mount.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_mount_types.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_mount_types.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_sources.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_sources.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_types.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volume_types.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volumes.py b/ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/volumes.py rename to ix-dev/stable/home-assistant/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/ix-app/app.yaml b/ix-dev/stable/ix-app/app.yaml index e6ba36c186..800aa762a2 100644 --- a/ix-dev/stable/ix-app/app.yaml +++ b/ix-dev/stable/ix-app/app.yaml @@ -7,8 +7,8 @@ home: https://www.truenas.com/ host_mounts: [] icon: https://media.sys.truenas.net/apps/ix-chart/icons/icon.webp keywords: [] -lib_version: 2.0.34 -lib_version_hash: 54c507c0a47e2a10aee421ec5a67c04f73692bd865d4d5057f57711e322a7951 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -19,4 +19,4 @@ screenshots: [] sources: [] title: iX App train: stable -version: 1.1.1 +version: 1.1.2 diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/deps.py b/ix-dev/stable/ix-app/templates/library/base_v2_0_34/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_deps.py b/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/__init__.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/__init__.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/configs.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/configs.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/container.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/depends.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/depends.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/deploy.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/deploy.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/device.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/device.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/dns.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/dns.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/error.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/error.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/formatter.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/formatter.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/labels.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/labels.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/notes.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/notes.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/portal.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/portal.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/portals.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/portals.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/ports.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/ports.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/render.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/render.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/resources.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/resources.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/restart.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/restart.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/__init__.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/__init__.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_build_image.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_build_image.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_configs.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_configs.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_depends.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_depends.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_dns.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_dns.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_formatter.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_formatter.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_labels.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_labels.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_notes.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_notes.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_portal.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_portal.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_ports.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_ports.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_render.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_render.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_resources.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_resources.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_restart.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/tests/test_restart.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_mount.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_mount.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_mount_types.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_mount_types.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_sources.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_sources.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_types.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/volume_types.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/ix-app/templates/library/base_v2_0_34/volumes.py b/ix-dev/stable/ix-app/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/ix-app/templates/library/base_v2_0_34/volumes.py rename to ix-dev/stable/ix-app/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/minio/app.yaml b/ix-dev/stable/minio/app.yaml index 80c2aa187c..f8b459a008 100644 --- a/ix-dev/stable/minio/app.yaml +++ b/ix-dev/stable/minio/app.yaml @@ -10,8 +10,8 @@ keywords: - storage - object-storage - S3 -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -31,4 +31,4 @@ sources: - https://github.com/minio/minio title: MinIO train: stable -version: 1.2.1 +version: 1.2.2 diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/container.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/deps.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/devices.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/environment.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/functions.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/functions.py deleted file mode 100644 index a8799c3963..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/functions.py +++ /dev/null @@ -1,111 +0,0 @@ -import re -import bcrypt -import secrets -from base64 import b64encode -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError -except ImportError: - from error import RenderError - - -class Functions: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def _bcrypt_hash(self, password): - hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") - return hashed - - def _htpasswd(self, username, password): - hashed = self._bcrypt_hash(password) - return username + ":" + hashed - - def _secure_string(self, length): - return secrets.token_urlsafe(length) - - def _basic_auth(self, username, password): - return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") - - def _basic_auth_header(self, username, password): - return f"Basic {self._basic_auth(username, password)}" - - def _fail(self, message): - raise RenderError(message) - - def _camel_case(self, string): - return string.title() - - def _auto_cast(self, value): - try: - return int(value) - except ValueError: - pass - - try: - return float(value) - except ValueError: - pass - - if value.lower() in ["true", "false"]: - return value.lower() == "true" - - return value - - def _match_regex(self, value, regex): - if not re.match(regex, value): - return False - return True - - def _must_match_regex(self, value, regex): - if not self._match_regex(value, regex): - raise RenderError(f"Expected [{value}] to match [{regex}]") - return value - - def _is_boolean(self, string): - return string.lower() in ["true", "false"] - - def _is_number(self, string): - try: - float(string) - return True - except ValueError: - return False - - def _copy_dict(self, dict): - return dict.copy() - - def _merge_dicts(self, *dicts): - merged_dict = {} - for dictionary in dicts: - merged_dict.update(dictionary) - return merged_dict - - def _disallow_chars(self, string, chars, key): - for char in chars: - if char in string: - raise RenderError(f"Disallowed character [{char}] in [{key}]") - - def func_map(self): - # TODO: Check what is no longer used and remove - return { - "auto_cast": self._auto_cast, - "basic_auth_header": self._basic_auth_header, - "basic_auth": self._basic_auth, - "bcrypt_hash": self._bcrypt_hash, - "camel_case": self._camel_case, - "copy_dict": self._copy_dict, - "fail": self._fail, - "htpasswd": self._htpasswd, - "is_boolean": self._is_boolean, - "is_number": self._is_number, - "match_regex": self._match_regex, - "merge_dicts": self._merge_dicts, - "must_match_regex": self._must_match_regex, - "secure_string": self._secure_string, - "disallow_chars": self._disallow_chars, - } diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/healthcheck.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_container.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_deps.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_device.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_environment.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_healthcheck.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/validations.py b/ix-dev/stable/minio/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/__init__.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/__init__.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/configs.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/configs.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/container.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/depends.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/depends.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/deploy.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/deploy.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/device.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/device.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/dns.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/dns.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/error.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/error.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/formatter.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/formatter.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/labels.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/labels.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/notes.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/notes.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/portal.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/portal.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/portals.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/portals.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/ports.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/ports.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/render.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/render.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/resources.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/resources.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/restart.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/restart.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/__init__.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/__init__.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_build_image.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_build_image.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_configs.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_configs.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_depends.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_depends.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_dns.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_dns.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_formatter.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_formatter.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_labels.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_labels.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_notes.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_notes.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_portal.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_portal.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_ports.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_ports.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_render.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_render.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_resources.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_resources.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_restart.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_restart.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/minio/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/volume_mount.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/volume_mount.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/volume_mount_types.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/volume_mount_types.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/volume_sources.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/volume_sources.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/volume_types.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/volume_types.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/volumes.py b/ix-dev/stable/minio/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/volumes.py rename to ix-dev/stable/minio/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/netdata/app.yaml b/ix-dev/stable/netdata/app.yaml index dc6965043e..2d41527b91 100644 --- a/ix-dev/stable/netdata/app.yaml +++ b/ix-dev/stable/netdata/app.yaml @@ -34,8 +34,8 @@ keywords: - alerting - metric - monitoring -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -58,4 +58,4 @@ sources: - https://github.com/netdata/netdata title: Netdata train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/container.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/netdata/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/netdata/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/container.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/device.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/error.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/render.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/netdata/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/netdata/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/netdata/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/netdata/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/netdata/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/nextcloud/app.yaml b/ix-dev/stable/nextcloud/app.yaml index 63283fd48d..bb0473ec16 100644 --- a/ix-dev/stable/nextcloud/app.yaml +++ b/ix-dev/stable/nextcloud/app.yaml @@ -28,8 +28,8 @@ keywords: - http - web - php -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -66,4 +66,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/nextcloud title: Nextcloud train: stable -version: 1.4.15 +version: 1.4.16 diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/container.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/deps.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/devices.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/environment.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/functions.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/functions.py deleted file mode 100644 index a8799c3963..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/functions.py +++ /dev/null @@ -1,111 +0,0 @@ -import re -import bcrypt -import secrets -from base64 import b64encode -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError -except ImportError: - from error import RenderError - - -class Functions: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def _bcrypt_hash(self, password): - hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") - return hashed - - def _htpasswd(self, username, password): - hashed = self._bcrypt_hash(password) - return username + ":" + hashed - - def _secure_string(self, length): - return secrets.token_urlsafe(length) - - def _basic_auth(self, username, password): - return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") - - def _basic_auth_header(self, username, password): - return f"Basic {self._basic_auth(username, password)}" - - def _fail(self, message): - raise RenderError(message) - - def _camel_case(self, string): - return string.title() - - def _auto_cast(self, value): - try: - return int(value) - except ValueError: - pass - - try: - return float(value) - except ValueError: - pass - - if value.lower() in ["true", "false"]: - return value.lower() == "true" - - return value - - def _match_regex(self, value, regex): - if not re.match(regex, value): - return False - return True - - def _must_match_regex(self, value, regex): - if not self._match_regex(value, regex): - raise RenderError(f"Expected [{value}] to match [{regex}]") - return value - - def _is_boolean(self, string): - return string.lower() in ["true", "false"] - - def _is_number(self, string): - try: - float(string) - return True - except ValueError: - return False - - def _copy_dict(self, dict): - return dict.copy() - - def _merge_dicts(self, *dicts): - merged_dict = {} - for dictionary in dicts: - merged_dict.update(dictionary) - return merged_dict - - def _disallow_chars(self, string, chars, key): - for char in chars: - if char in string: - raise RenderError(f"Disallowed character [{char}] in [{key}]") - - def func_map(self): - # TODO: Check what is no longer used and remove - return { - "auto_cast": self._auto_cast, - "basic_auth_header": self._basic_auth_header, - "basic_auth": self._basic_auth, - "bcrypt_hash": self._bcrypt_hash, - "camel_case": self._camel_case, - "copy_dict": self._copy_dict, - "fail": self._fail, - "htpasswd": self._htpasswd, - "is_boolean": self._is_boolean, - "is_number": self._is_number, - "match_regex": self._match_regex, - "merge_dicts": self._merge_dicts, - "must_match_regex": self._must_match_regex, - "secure_string": self._secure_string, - "disallow_chars": self._disallow_chars, - } diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/healthcheck.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/storage.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/storage.py deleted file mode 100644 index 3e5b629790..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/storage.py +++ /dev/null @@ -1,106 +0,0 @@ -from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .validations import valid_fs_path_or_raise - from .volume_mount import VolumeMount -except ImportError: - from error import RenderError - from validations import valid_fs_path_or_raise - from volume_mount import VolumeMount - - -class IxStorageTmpfsConfig(TypedDict): - size: NotRequired[int] - mode: NotRequired[str] - - -class AclConfig(TypedDict, total=False): - path: str - - -class IxStorageHostPathConfig(TypedDict): - path: NotRequired[str] # Either this or acl.path must be set - acl_enable: NotRequired[bool] - acl: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageIxVolumeConfig(TypedDict): - dataset_name: str - acl_enable: NotRequired[bool] - acl_entries: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageVolumeConfig(TypedDict): - volume_name: NotRequired[str] - nocopy: NotRequired[bool] - auto_permissions: NotRequired[bool] - - -class IxStorageNfsConfig(TypedDict): - server: str - path: str - options: NotRequired[list[str]] - - -class IxStorageCifsConfig(TypedDict): - server: str - path: str - username: str - password: str - domain: NotRequired[str] - options: NotRequired[list[str]] - - -IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] -IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] -IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] - - -class IxStorage(TypedDict): - type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] - read_only: NotRequired[bool] - - ix_volume_config: NotRequired[IxStorageIxVolumeConfig] - host_path_config: NotRequired[IxStorageHostPathConfig] - tmpfs_config: NotRequired[IxStorageTmpfsConfig] - volume_config: NotRequired[IxStorageVolumeConfig] - nfs_config: NotRequired[IxStorageNfsConfig] - cifs_config: NotRequired[IxStorageCifsConfig] - - -class Storage: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._volume_mounts: set[VolumeMount] = set() - - def add(self, mount_path: str, config: "IxStorage"): - mount_path = valid_fs_path_or_raise(mount_path) - if mount_path in [m.mount_path for m in self._volume_mounts]: - raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") - - volume_mount = VolumeMount(self._render_instance, mount_path, config) - self._volume_mounts.add(volume_mount) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - cfg: "IxStorage" = { - "type": "host_path", - "read_only": read_only, - "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, - } - self.add(mount_path, cfg) - - def has_mounts(self) -> bool: - return bool(self._volume_mounts) - - def render(self): - return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_container.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_deps.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_device.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_environment.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_functions.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_functions.py deleted file mode 100644 index a75e7c4084..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_functions.py +++ /dev/null @@ -1,65 +0,0 @@ -import re -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_funcs(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - tests = [ - {"func": "auto_cast", "values": ["1"], "expected": 1}, - {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, - {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, - { - "func": "bcrypt_hash", - "values": ["my_pass"], - "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, - {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, - {"func": "fail", "values": ["my_message"], "expect_raise": True}, - { - "func": "htpasswd", - "values": ["my_user", "my_pass"], - "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "is_boolean", "values": ["true"], "expected": True}, - {"func": "is_boolean", "values": ["false"], "expected": True}, - {"func": "is_number", "values": ["1"], "expected": True}, - {"func": "is_number", "values": ["1.1"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, - {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, - {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, - {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, - {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, - ] - - for test in tests: - print(test["func"], test) - func = render.funcs[test["func"]] - if test.get("expect_raise", False): - with pytest.raises(Exception): - func(*test["values"]) - elif test.get("expect_regex"): - r = func(*test["values"]) - assert re.match(test["expect_regex"], r) is not None - else: - r = func(*test["values"]) - assert r == test["expected"] diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_healthcheck.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_volumes.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_volumes.py deleted file mode 100644 index e0ae9a6953..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_volumes.py +++ /dev/null @@ -1,666 +0,0 @@ -import pytest - - -from render import Render -from formatter import get_hashed_name_for_volume - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_volume_invalid_type(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "invalid_type"}) - - -def test_add_volume_empty_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("", {"type": "tmpfs"}) - - -def test_add_volume_duplicate_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_storage("/some/path", {"type": "tmpfs"}) - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "tmpfs"}) - - -def test_add_volume_host_path_invalid_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_host_path_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path"} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_with_acl_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_mount(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_acl(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, - } - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test/acl", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "slave"}, - } - ] - - -def test_add_host_path_volume_mount_with_create_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_invalid_dataset_name(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_no_ix_volume_config(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume"} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_volume_mount(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_volume_mount_with_options(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = { - "type": "ix_volume", - "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, - } - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rslave"}, - } - ] - - -def test_cifs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_username(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_password(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_without_cifs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["verbose=true", "verbose=true"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["user=username"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": {"verbose": True}, - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": [{"verbose": True}], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_add_cifs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_cifs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["vers=3.0", "verbose=true"], - } - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "cifs", - "device": "//server/path", - "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_without_nfs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = { - "type": "nfs", - "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_add_nfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path"} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "nfs", - "device": ":/path", - "o": "addr=server,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_tmpfs_invalid_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_zero_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_invalid_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs"} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "tmpfs", - "target": "/some/path", - "read_only": False, - } - ] - - -def test_temporary_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "source": "test_temp_volume", - "type": "volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - - -def test_docker_volume_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume_missing_volume_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["volumes"] == {"test_volume": {}} - - -def test_anonymous_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} - ] - assert "volumes" not in output - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_not_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/validations.py b/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/__init__.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/__init__.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/configs.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/configs.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/container.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/depends.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/depends.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/deploy.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/deploy.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/device.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/device.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/dns.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/dns.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/error.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/error.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/formatter.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/formatter.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/functions.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/functions.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/functions.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/functions.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/labels.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/labels.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/notes.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/notes.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/portal.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/portal.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/portals.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/portals.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/ports.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/ports.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/render.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/render.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/resources.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/resources.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/restart.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/restart.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/__init__.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/__init__.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_build_image.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_build_image.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_configs.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_configs.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_depends.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_depends.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_dns.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_dns.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_formatter.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_formatter.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_labels.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_labels.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_notes.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_notes.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_portal.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_portal.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_ports.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_ports.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_render.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_render.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_resources.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_resources.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_restart.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/tests/test_restart.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_mount.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_mount.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_mount_types.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_mount_types.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_sources.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_sources.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_types.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volume_types.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volumes.py b/ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/nextcloud/templates/library/base_v2_0_21/volumes.py rename to ix-dev/stable/nextcloud/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/photoprism/app.yaml b/ix-dev/stable/photoprism/app.yaml index a847135121..c3ec80e880 100644 --- a/ix-dev/stable/photoprism/app.yaml +++ b/ix-dev/stable/photoprism/app.yaml @@ -22,8 +22,8 @@ keywords: - media - photos - image -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -42,4 +42,4 @@ sources: - https://photoprism.app/ title: Photoprism train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/container.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/photoprism/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/container.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/device.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/error.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/functions.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/functions.py similarity index 99% rename from ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/functions.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/functions.py index 47a2c1233a..7d082d8c46 100644 --- a/ix-dev/stable/diskoverdata/templates/library/base_v2_0_31/functions.py +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -79,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/render.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/storage.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/storage.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/storage.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/storage.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/sysctls.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/sysctls.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/sysctls.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_functions.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_functions.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_sysctls.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_sysctls.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_volumes.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_volumes.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/photoprism/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/photoprism/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/photoprism/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/photoprism/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/pihole/app.yaml b/ix-dev/stable/pihole/app.yaml index 6ba4776476..f7fbd40181 100644 --- a/ix-dev/stable/pihole/app.yaml +++ b/ix-dev/stable/pihole/app.yaml @@ -33,8 +33,8 @@ icon: https://media.sys.truenas.net/apps/pihole/icons/icon.png keywords: - networking - dns -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -53,4 +53,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/pihole title: Pi-hole train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/container.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/pihole/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/pihole/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/container.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/device.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/error.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/functions.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/functions.py similarity index 63% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/functions.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/functions.py index a8799c3963..7d082d8c46 100644 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/functions.py +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -9,8 +10,10 @@ try: from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource except ImportError: from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource class Functions: @@ -77,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} @@ -85,10 +88,42 @@ def _merge_dicts(self, *dicts): merged_dict.update(dictionary) return merged_dict - def _disallow_chars(self, string, chars, key): + def _disallow_chars(self, string: str, chars: list[str], key: str): for char in chars: if char in string: raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") def func_map(self): # TODO: Check what is no longer used and remove @@ -108,4 +143,7 @@ def func_map(self): "must_match_regex": self._must_match_regex, "secure_string": self._secure_string, "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, } diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/render.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/storage.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/storage.py similarity index 87% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/storage.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/storage.py +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/sysctls.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_functions.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_functions.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_functions.py +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_sysctls.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_volumes.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_volumes.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/ix-dev/stable/pihole/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/pihole/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/pihole/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/pihole/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/pihole/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/pihole/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/plex/app.yaml b/ix-dev/stable/plex/app.yaml index 3019d5a922..6749a87e05 100644 --- a/ix-dev/stable/plex/app.yaml +++ b/ix-dev/stable/plex/app.yaml @@ -27,8 +27,8 @@ keywords: - series - tv - streaming -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -48,4 +48,4 @@ sources: - https://hub.docker.com/r/plexinc/pms-docker title: Plex train: stable -version: 1.1.4 +version: 1.1.5 diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/container.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/deps.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/devices.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/environment.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/functions.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/functions.py deleted file mode 100644 index a8799c3963..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/functions.py +++ /dev/null @@ -1,111 +0,0 @@ -import re -import bcrypt -import secrets -from base64 import b64encode -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError -except ImportError: - from error import RenderError - - -class Functions: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def _bcrypt_hash(self, password): - hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") - return hashed - - def _htpasswd(self, username, password): - hashed = self._bcrypt_hash(password) - return username + ":" + hashed - - def _secure_string(self, length): - return secrets.token_urlsafe(length) - - def _basic_auth(self, username, password): - return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") - - def _basic_auth_header(self, username, password): - return f"Basic {self._basic_auth(username, password)}" - - def _fail(self, message): - raise RenderError(message) - - def _camel_case(self, string): - return string.title() - - def _auto_cast(self, value): - try: - return int(value) - except ValueError: - pass - - try: - return float(value) - except ValueError: - pass - - if value.lower() in ["true", "false"]: - return value.lower() == "true" - - return value - - def _match_regex(self, value, regex): - if not re.match(regex, value): - return False - return True - - def _must_match_regex(self, value, regex): - if not self._match_regex(value, regex): - raise RenderError(f"Expected [{value}] to match [{regex}]") - return value - - def _is_boolean(self, string): - return string.lower() in ["true", "false"] - - def _is_number(self, string): - try: - float(string) - return True - except ValueError: - return False - - def _copy_dict(self, dict): - return dict.copy() - - def _merge_dicts(self, *dicts): - merged_dict = {} - for dictionary in dicts: - merged_dict.update(dictionary) - return merged_dict - - def _disallow_chars(self, string, chars, key): - for char in chars: - if char in string: - raise RenderError(f"Disallowed character [{char}] in [{key}]") - - def func_map(self): - # TODO: Check what is no longer used and remove - return { - "auto_cast": self._auto_cast, - "basic_auth_header": self._basic_auth_header, - "basic_auth": self._basic_auth, - "bcrypt_hash": self._bcrypt_hash, - "camel_case": self._camel_case, - "copy_dict": self._copy_dict, - "fail": self._fail, - "htpasswd": self._htpasswd, - "is_boolean": self._is_boolean, - "is_number": self._is_number, - "match_regex": self._match_regex, - "merge_dicts": self._merge_dicts, - "must_match_regex": self._must_match_regex, - "secure_string": self._secure_string, - "disallow_chars": self._disallow_chars, - } diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/healthcheck.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/storage.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/storage.py deleted file mode 100644 index 3e5b629790..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/storage.py +++ /dev/null @@ -1,106 +0,0 @@ -from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .validations import valid_fs_path_or_raise - from .volume_mount import VolumeMount -except ImportError: - from error import RenderError - from validations import valid_fs_path_or_raise - from volume_mount import VolumeMount - - -class IxStorageTmpfsConfig(TypedDict): - size: NotRequired[int] - mode: NotRequired[str] - - -class AclConfig(TypedDict, total=False): - path: str - - -class IxStorageHostPathConfig(TypedDict): - path: NotRequired[str] # Either this or acl.path must be set - acl_enable: NotRequired[bool] - acl: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageIxVolumeConfig(TypedDict): - dataset_name: str - acl_enable: NotRequired[bool] - acl_entries: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageVolumeConfig(TypedDict): - volume_name: NotRequired[str] - nocopy: NotRequired[bool] - auto_permissions: NotRequired[bool] - - -class IxStorageNfsConfig(TypedDict): - server: str - path: str - options: NotRequired[list[str]] - - -class IxStorageCifsConfig(TypedDict): - server: str - path: str - username: str - password: str - domain: NotRequired[str] - options: NotRequired[list[str]] - - -IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] -IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] -IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] - - -class IxStorage(TypedDict): - type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] - read_only: NotRequired[bool] - - ix_volume_config: NotRequired[IxStorageIxVolumeConfig] - host_path_config: NotRequired[IxStorageHostPathConfig] - tmpfs_config: NotRequired[IxStorageTmpfsConfig] - volume_config: NotRequired[IxStorageVolumeConfig] - nfs_config: NotRequired[IxStorageNfsConfig] - cifs_config: NotRequired[IxStorageCifsConfig] - - -class Storage: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._volume_mounts: set[VolumeMount] = set() - - def add(self, mount_path: str, config: "IxStorage"): - mount_path = valid_fs_path_or_raise(mount_path) - if mount_path in [m.mount_path for m in self._volume_mounts]: - raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") - - volume_mount = VolumeMount(self._render_instance, mount_path, config) - self._volume_mounts.add(volume_mount) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - cfg: "IxStorage" = { - "type": "host_path", - "read_only": read_only, - "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, - } - self.add(mount_path, cfg) - - def has_mounts(self) -> bool: - return bool(self._volume_mounts) - - def render(self): - return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_container.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_deps.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_device.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_environment.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_functions.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_functions.py deleted file mode 100644 index a75e7c4084..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_functions.py +++ /dev/null @@ -1,65 +0,0 @@ -import re -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_funcs(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - tests = [ - {"func": "auto_cast", "values": ["1"], "expected": 1}, - {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, - {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, - { - "func": "bcrypt_hash", - "values": ["my_pass"], - "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, - {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, - {"func": "fail", "values": ["my_message"], "expect_raise": True}, - { - "func": "htpasswd", - "values": ["my_user", "my_pass"], - "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "is_boolean", "values": ["true"], "expected": True}, - {"func": "is_boolean", "values": ["false"], "expected": True}, - {"func": "is_number", "values": ["1"], "expected": True}, - {"func": "is_number", "values": ["1.1"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, - {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, - {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, - {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, - {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, - ] - - for test in tests: - print(test["func"], test) - func = render.funcs[test["func"]] - if test.get("expect_raise", False): - with pytest.raises(Exception): - func(*test["values"]) - elif test.get("expect_regex"): - r = func(*test["values"]) - assert re.match(test["expect_regex"], r) is not None - else: - r = func(*test["values"]) - assert r == test["expected"] diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_healthcheck.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_volumes.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_volumes.py deleted file mode 100644 index e0ae9a6953..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_volumes.py +++ /dev/null @@ -1,666 +0,0 @@ -import pytest - - -from render import Render -from formatter import get_hashed_name_for_volume - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_volume_invalid_type(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "invalid_type"}) - - -def test_add_volume_empty_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("", {"type": "tmpfs"}) - - -def test_add_volume_duplicate_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_storage("/some/path", {"type": "tmpfs"}) - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "tmpfs"}) - - -def test_add_volume_host_path_invalid_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_host_path_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path"} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_with_acl_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_mount(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_acl(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, - } - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test/acl", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "slave"}, - } - ] - - -def test_add_host_path_volume_mount_with_create_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_invalid_dataset_name(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_no_ix_volume_config(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume"} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_volume_mount(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_volume_mount_with_options(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = { - "type": "ix_volume", - "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, - } - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rslave"}, - } - ] - - -def test_cifs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_username(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_password(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_without_cifs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["verbose=true", "verbose=true"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["user=username"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": {"verbose": True}, - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": [{"verbose": True}], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_add_cifs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_cifs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["vers=3.0", "verbose=true"], - } - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "cifs", - "device": "//server/path", - "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_without_nfs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = { - "type": "nfs", - "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_add_nfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path"} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "nfs", - "device": ":/path", - "o": "addr=server,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_tmpfs_invalid_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_zero_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_invalid_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs"} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "tmpfs", - "target": "/some/path", - "read_only": False, - } - ] - - -def test_temporary_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "source": "test_temp_volume", - "type": "volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - - -def test_docker_volume_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume_missing_volume_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["volumes"] == {"test_volume": {}} - - -def test_anonymous_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} - ] - assert "volumes" not in output - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_not_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/validations.py b/ix-dev/stable/plex/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/ix-dev/stable/plex/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/__init__.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/__init__.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/configs.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/configs.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/container.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/depends.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/depends.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/deploy.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/deploy.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/device.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/device.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/dns.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/dns.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/error.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/error.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/formatter.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/formatter.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/functions.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/functions.py similarity index 63% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/functions.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/functions.py index a8799c3963..7d082d8c46 100644 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/functions.py +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -9,8 +10,10 @@ try: from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource except ImportError: from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource class Functions: @@ -77,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} @@ -85,10 +88,42 @@ def _merge_dicts(self, *dicts): merged_dict.update(dictionary) return merged_dict - def _disallow_chars(self, string, chars, key): + def _disallow_chars(self, string: str, chars: list[str], key: str): for char in chars: if char in string: raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") def func_map(self): # TODO: Check what is no longer used and remove @@ -108,4 +143,7 @@ def func_map(self): "must_match_regex": self._must_match_regex, "secure_string": self._secure_string, "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, } diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/labels.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/labels.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/notes.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/notes.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/portal.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/portal.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/portals.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/portals.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/ports.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/ports.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/render.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/render.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/resources.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/resources.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/restart.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/restart.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/storage.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/storage.py similarity index 87% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/storage.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/storage.py +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/sysctls.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/__init__.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/__init__.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_build_image.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_build_image.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_configs.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_configs.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_depends.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_depends.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_dns.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_dns.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_formatter.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_formatter.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_functions.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_functions.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/tests/test_functions.py +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_labels.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_labels.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_notes.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_notes.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_portal.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_portal.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_ports.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_ports.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_render.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_render.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_resources.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_resources.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_restart.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/tests/test_restart.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_sysctls.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_volumes.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_volumes.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/ix-dev/stable/plex/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/plex/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/volume_mount.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/volume_mount.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/volume_mount_types.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/volume_mount_types.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/volume_sources.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/volume_sources.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/volume_types.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/volume_types.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/plex/templates/library/base_v2_0_21/volumes.py b/ix-dev/stable/plex/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/plex/templates/library/base_v2_0_21/volumes.py rename to ix-dev/stable/plex/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/prometheus/app.yaml b/ix-dev/stable/prometheus/app.yaml index 00ab5ce03f..698eef10eb 100644 --- a/ix-dev/stable/prometheus/app.yaml +++ b/ix-dev/stable/prometheus/app.yaml @@ -9,8 +9,8 @@ icon: https://media.sys.truenas.net/apps/prometheus/icons/icon.png keywords: - metrics - prometheus -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -30,4 +30,4 @@ sources: - https://prometheus.io title: Prometheus train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/container.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/prometheus/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/container.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/device.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/error.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/functions.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/functions.py similarity index 63% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/functions.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/functions.py index a8799c3963..7d082d8c46 100644 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/functions.py +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -9,8 +10,10 @@ try: from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource except ImportError: from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource class Functions: @@ -77,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} @@ -85,10 +88,42 @@ def _merge_dicts(self, *dicts): merged_dict.update(dictionary) return merged_dict - def _disallow_chars(self, string, chars, key): + def _disallow_chars(self, string: str, chars: list[str], key: str): for char in chars: if char in string: raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") def func_map(self): # TODO: Check what is no longer used and remove @@ -108,4 +143,7 @@ def func_map(self): "must_match_regex": self._must_match_regex, "secure_string": self._secure_string, "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, } diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/render.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/storage.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/storage.py similarity index 87% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/storage.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/storage.py +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/sysctls.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_functions.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_functions.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/ix-dev/stable/home-assistant/templates/library/base_v2_0_21/tests/test_functions.py +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_sysctls.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_volumes.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_volumes.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/ix-dev/enterprise/asigra-ds-system/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/prometheus/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/prometheus/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/prometheus/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/prometheus/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/storj/app.yaml b/ix-dev/stable/storj/app.yaml index ae28ba5bf5..79c16e3f44 100644 --- a/ix-dev/stable/storj/app.yaml +++ b/ix-dev/stable/storj/app.yaml @@ -18,8 +18,8 @@ keywords: - networking - financial - file-sharing -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -37,4 +37,4 @@ sources: - https://www.storj.io title: Storj train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/container.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/storj/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/storj/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/container.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/device.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/error.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/functions.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/functions.py new file mode 100644 index 0000000000..7d082d8c46 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/functions.py @@ -0,0 +1,149 @@ +import re +import copy +import bcrypt +import secrets +from base64 import b64encode +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource +except ImportError: + from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource + + +class Functions: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def _bcrypt_hash(self, password): + hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + return hashed + + def _htpasswd(self, username, password): + hashed = self._bcrypt_hash(password) + return username + ":" + hashed + + def _secure_string(self, length): + return secrets.token_urlsafe(length) + + def _basic_auth(self, username, password): + return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") + + def _basic_auth_header(self, username, password): + return f"Basic {self._basic_auth(username, password)}" + + def _fail(self, message): + raise RenderError(message) + + def _camel_case(self, string): + return string.title() + + def _auto_cast(self, value): + try: + return int(value) + except ValueError: + pass + + try: + return float(value) + except ValueError: + pass + + if value.lower() in ["true", "false"]: + return value.lower() == "true" + + return value + + def _match_regex(self, value, regex): + if not re.match(regex, value): + return False + return True + + def _must_match_regex(self, value, regex): + if not self._match_regex(value, regex): + raise RenderError(f"Expected [{value}] to match [{regex}]") + return value + + def _is_boolean(self, string): + return string.lower() in ["true", "false"] + + def _is_number(self, string): + try: + float(string) + return True + except ValueError: + return False + + def _copy_dict(self, dict): + return copy.deepcopy(dict) + + def _merge_dicts(self, *dicts): + merged_dict = {} + for dictionary in dicts: + merged_dict.update(dictionary) + return merged_dict + + def _disallow_chars(self, string: str, chars: list[str], key: str): + for char in chars: + if char in string: + raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") + + def func_map(self): + # TODO: Check what is no longer used and remove + return { + "auto_cast": self._auto_cast, + "basic_auth_header": self._basic_auth_header, + "basic_auth": self._basic_auth, + "bcrypt_hash": self._bcrypt_hash, + "camel_case": self._camel_case, + "copy_dict": self._copy_dict, + "fail": self._fail, + "htpasswd": self._htpasswd, + "is_boolean": self._is_boolean, + "is_number": self._is_number, + "match_regex": self._match_regex, + "merge_dicts": self._merge_dicts, + "must_match_regex": self._must_match_regex, + "secure_string": self._secure_string, + "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, + } diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/render.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/emby/templates/library/base_v2_0_21/storage.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/storage.py similarity index 87% rename from ix-dev/stable/emby/templates/library/base_v2_0_21/storage.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/ix-dev/stable/emby/templates/library/base_v2_0_21/storage.py +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/sysctls.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_functions.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_functions.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_functions.py +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_sysctls.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_volumes.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_volumes.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/ix-dev/stable/minio/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/ix-dev/stable/storj/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/storj/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/storj/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/storj/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/storj/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/storj/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/syncthing/app.yaml b/ix-dev/stable/syncthing/app.yaml index 8abff7400a..c8d8a17e5b 100644 --- a/ix-dev/stable/syncthing/app.yaml +++ b/ix-dev/stable/syncthing/app.yaml @@ -26,8 +26,8 @@ keywords: - sync - file-sharing - backup -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -50,4 +50,4 @@ sources: - https://hub.docker.com/r/syncthing/syncthing title: Syncthing train: stable -version: 1.1.0 +version: 1.1.1 diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/container.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/syncthing/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/container.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/device.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/error.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/functions.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/functions.py new file mode 100644 index 0000000000..7d082d8c46 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/functions.py @@ -0,0 +1,149 @@ +import re +import copy +import bcrypt +import secrets +from base64 import b64encode +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource +except ImportError: + from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource + + +class Functions: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def _bcrypt_hash(self, password): + hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + return hashed + + def _htpasswd(self, username, password): + hashed = self._bcrypt_hash(password) + return username + ":" + hashed + + def _secure_string(self, length): + return secrets.token_urlsafe(length) + + def _basic_auth(self, username, password): + return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") + + def _basic_auth_header(self, username, password): + return f"Basic {self._basic_auth(username, password)}" + + def _fail(self, message): + raise RenderError(message) + + def _camel_case(self, string): + return string.title() + + def _auto_cast(self, value): + try: + return int(value) + except ValueError: + pass + + try: + return float(value) + except ValueError: + pass + + if value.lower() in ["true", "false"]: + return value.lower() == "true" + + return value + + def _match_regex(self, value, regex): + if not re.match(regex, value): + return False + return True + + def _must_match_regex(self, value, regex): + if not self._match_regex(value, regex): + raise RenderError(f"Expected [{value}] to match [{regex}]") + return value + + def _is_boolean(self, string): + return string.lower() in ["true", "false"] + + def _is_number(self, string): + try: + float(string) + return True + except ValueError: + return False + + def _copy_dict(self, dict): + return copy.deepcopy(dict) + + def _merge_dicts(self, *dicts): + merged_dict = {} + for dictionary in dicts: + merged_dict.update(dictionary) + return merged_dict + + def _disallow_chars(self, string: str, chars: list[str], key: str): + for char in chars: + if char in string: + raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") + + def func_map(self): + # TODO: Check what is no longer used and remove + return { + "auto_cast": self._auto_cast, + "basic_auth_header": self._basic_auth_header, + "basic_auth": self._basic_auth, + "bcrypt_hash": self._bcrypt_hash, + "camel_case": self._camel_case, + "copy_dict": self._copy_dict, + "fail": self._fail, + "htpasswd": self._htpasswd, + "is_boolean": self._is_boolean, + "is_number": self._is_number, + "match_regex": self._match_regex, + "merge_dicts": self._merge_dicts, + "must_match_regex": self._must_match_regex, + "secure_string": self._secure_string, + "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, + } diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/render.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/storage.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/storage.py new file mode 100644 index 0000000000..e697ba902a --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/storage.py @@ -0,0 +1,116 @@ +from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .validations import valid_fs_path_or_raise + from .volume_mount import VolumeMount +except ImportError: + from error import RenderError + from validations import valid_fs_path_or_raise + from volume_mount import VolumeMount + + +class IxStorageTmpfsConfig(TypedDict): + size: NotRequired[int] + mode: NotRequired[str] + + +class AclConfig(TypedDict, total=False): + path: str + + +class IxStorageHostPathConfig(TypedDict): + path: NotRequired[str] # Either this or acl.path must be set + acl_enable: NotRequired[bool] + acl: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageIxVolumeConfig(TypedDict): + dataset_name: str + acl_enable: NotRequired[bool] + acl_entries: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageVolumeConfig(TypedDict): + volume_name: NotRequired[str] + nocopy: NotRequired[bool] + auto_permissions: NotRequired[bool] + + +class IxStorageNfsConfig(TypedDict): + server: str + path: str + options: NotRequired[list[str]] + + +class IxStorageCifsConfig(TypedDict): + server: str + path: str + username: str + password: str + domain: NotRequired[str] + options: NotRequired[list[str]] + + +IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] +IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] +IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] + + +class IxStorage(TypedDict): + type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] + read_only: NotRequired[bool] + + ix_volume_config: NotRequired[IxStorageIxVolumeConfig] + host_path_config: NotRequired[IxStorageHostPathConfig] + tmpfs_config: NotRequired[IxStorageTmpfsConfig] + volume_config: NotRequired[IxStorageVolumeConfig] + nfs_config: NotRequired[IxStorageNfsConfig] + cifs_config: NotRequired[IxStorageCifsConfig] + + +class Storage: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._volume_mounts: set[VolumeMount] = set() + + def add(self, mount_path: str, config: "IxStorage"): + mount_path = valid_fs_path_or_raise(mount_path) + if mount_path in [m.mount_path for m in self._volume_mounts]: + raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") + + volume_mount = VolumeMount(self._render_instance, mount_path, config) + self._volume_mounts.add(volume_mount) + + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def has_mounts(self) -> bool: + return bool(self._volume_mounts) + + def render(self): + return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/sysctls.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_functions.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_functions.py new file mode 100644 index 0000000000..0ea3b57d18 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_functions.py @@ -0,0 +1,88 @@ +import re +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + tests = [ + {"func": "auto_cast", "values": ["1"], "expected": 1}, + {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, + {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, + { + "func": "bcrypt_hash", + "values": ["my_pass"], + "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, + {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, + {"func": "fail", "values": ["my_message"], "expect_raise": True}, + { + "func": "htpasswd", + "values": ["my_user", "my_pass"], + "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "is_boolean", "values": ["true"], "expected": True}, + {"func": "is_boolean", "values": ["false"], "expected": True}, + {"func": "is_number", "values": ["1"], "expected": True}, + {"func": "is_number", "values": ["1.1"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, + {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, + {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, + {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, + {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, + ] + + for test in tests: + print(test["func"], test) + func = render.funcs[test["func"]] + if test.get("expect_raise", False): + with pytest.raises(Exception): + func(*test["values"]) + elif test.get("expect_regex"): + r = func(*test["values"]) + assert re.match(test["expect_regex"], r) is not None + else: + r = func(*test["values"]) + assert r == test["expected"] diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_sysctls.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_volumes.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_volumes.py new file mode 100644 index 0000000000..aef0d39481 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/tests/test_volumes.py @@ -0,0 +1,666 @@ +import pytest + + +from render import Render +from formatter import get_hashed_name_for_volume + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_volume_invalid_type(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "invalid_type"}) + + +def test_add_volume_empty_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("", {"type": "tmpfs"}) + + +def test_add_volume_duplicate_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_storage("/some/path", {"type": "tmpfs"}) + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "tmpfs"}) + + +def test_add_volume_host_path_invalid_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_host_path_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path"} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_with_acl_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_mount(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_acl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, + } + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test/acl", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "slave"}, + } + ] + + +def test_add_host_path_volume_mount_with_create_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_invalid_dataset_name(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_no_ix_volume_config(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume"} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_volume_mount(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_volume_mount_with_options(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = { + "type": "ix_volume", + "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, + } + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rslave"}, + } + ] + + +def test_cifs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_username(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_password(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_without_cifs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["verbose=true", "verbose=true"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["user=username"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": {"verbose": True}, + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": [{"verbose": True}], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_add_cifs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_cifs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["vers=3.0", "verbose=true"], + } + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "cifs", + "device": "//server/path", + "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_without_nfs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = { + "type": "nfs", + "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_add_nfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path"} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "nfs", + "device": ":/path", + "o": "addr=server,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_tmpfs_invalid_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_zero_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_invalid_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs"} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "tmpfs", + "target": "/some/path", + "read_only": False, + } + ] + + +def test_temporary_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "source": "test_temp_volume", + "type": "volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + + +def test_docker_volume_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume_missing_volume_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["volumes"] == {"test_volume": {}} + + +def test_anonymous_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} + ] + assert "volumes" not in output + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_not_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/some/path") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/syncthing/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/syncthing/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/syncthing/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/syncthing/templates/library/base_v2_1_0/volumes.py diff --git a/ix-dev/stable/wg-easy/app.yaml b/ix-dev/stable/wg-easy/app.yaml index b878003f67..55aec87572 100644 --- a/ix-dev/stable/wg-easy/app.yaml +++ b/ix-dev/stable/wg-easy/app.yaml @@ -16,8 +16,8 @@ keywords: - wireguard - network - vpn -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -35,4 +35,4 @@ sources: - https://github.com/wg-easy/wg-easy title: WG Easy train: stable -version: 1.1.1 +version: 1.1.2 diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/container.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/deps.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/devices.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/environment.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/healthcheck.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_container.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_deps.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_device.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_environment.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_healthcheck.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/validations.py b/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/__init__.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/__init__.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/__init__.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/configs.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/configs.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/configs.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/configs.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/container.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/depends.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/depends.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/depends.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/depends.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/deploy.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/deploy.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deploy.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_mariadb.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_perms.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_postgres.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_redis.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/device.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/device.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/device.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/device.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/devices.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/dns.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/dns.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/dns.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/dns.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/environment.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/error.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/error.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/error.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/error.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/formatter.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/formatter.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/formatter.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/functions.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/functions.py new file mode 100644 index 0000000000..7d082d8c46 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/functions.py @@ -0,0 +1,149 @@ +import re +import copy +import bcrypt +import secrets +from base64 import b64encode +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource +except ImportError: + from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource + + +class Functions: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def _bcrypt_hash(self, password): + hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + return hashed + + def _htpasswd(self, username, password): + hashed = self._bcrypt_hash(password) + return username + ":" + hashed + + def _secure_string(self, length): + return secrets.token_urlsafe(length) + + def _basic_auth(self, username, password): + return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") + + def _basic_auth_header(self, username, password): + return f"Basic {self._basic_auth(username, password)}" + + def _fail(self, message): + raise RenderError(message) + + def _camel_case(self, string): + return string.title() + + def _auto_cast(self, value): + try: + return int(value) + except ValueError: + pass + + try: + return float(value) + except ValueError: + pass + + if value.lower() in ["true", "false"]: + return value.lower() == "true" + + return value + + def _match_regex(self, value, regex): + if not re.match(regex, value): + return False + return True + + def _must_match_regex(self, value, regex): + if not self._match_regex(value, regex): + raise RenderError(f"Expected [{value}] to match [{regex}]") + return value + + def _is_boolean(self, string): + return string.lower() in ["true", "false"] + + def _is_number(self, string): + try: + float(string) + return True + except ValueError: + return False + + def _copy_dict(self, dict): + return copy.deepcopy(dict) + + def _merge_dicts(self, *dicts): + merged_dict = {} + for dictionary in dicts: + merged_dict.update(dictionary) + return merged_dict + + def _disallow_chars(self, string: str, chars: list[str], key: str): + for char in chars: + if char in string: + raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") + + def func_map(self): + # TODO: Check what is no longer used and remove + return { + "auto_cast": self._auto_cast, + "basic_auth_header": self._basic_auth_header, + "basic_auth": self._basic_auth, + "bcrypt_hash": self._bcrypt_hash, + "camel_case": self._camel_case, + "copy_dict": self._copy_dict, + "fail": self._fail, + "htpasswd": self._htpasswd, + "is_boolean": self._is_boolean, + "is_number": self._is_number, + "match_regex": self._match_regex, + "merge_dicts": self._merge_dicts, + "must_match_regex": self._must_match_regex, + "secure_string": self._secure_string, + "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, + } diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/healthcheck.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/labels.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/labels.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/labels.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/labels.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/notes.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/notes.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/notes.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/notes.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/portal.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/portal.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/portal.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/portal.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/portals.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/portals.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/portals.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/portals.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/ports.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/ports.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/ports.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/ports.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/render.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/render.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/render.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/render.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/resources.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/resources.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/resources.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/resources.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/restart.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/restart.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/restart.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/restart.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/storage.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/storage.py new file mode 100644 index 0000000000..e697ba902a --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/storage.py @@ -0,0 +1,116 @@ +from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .validations import valid_fs_path_or_raise + from .volume_mount import VolumeMount +except ImportError: + from error import RenderError + from validations import valid_fs_path_or_raise + from volume_mount import VolumeMount + + +class IxStorageTmpfsConfig(TypedDict): + size: NotRequired[int] + mode: NotRequired[str] + + +class AclConfig(TypedDict, total=False): + path: str + + +class IxStorageHostPathConfig(TypedDict): + path: NotRequired[str] # Either this or acl.path must be set + acl_enable: NotRequired[bool] + acl: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageIxVolumeConfig(TypedDict): + dataset_name: str + acl_enable: NotRequired[bool] + acl_entries: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageVolumeConfig(TypedDict): + volume_name: NotRequired[str] + nocopy: NotRequired[bool] + auto_permissions: NotRequired[bool] + + +class IxStorageNfsConfig(TypedDict): + server: str + path: str + options: NotRequired[list[str]] + + +class IxStorageCifsConfig(TypedDict): + server: str + path: str + username: str + password: str + domain: NotRequired[str] + options: NotRequired[list[str]] + + +IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] +IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] +IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] + + +class IxStorage(TypedDict): + type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] + read_only: NotRequired[bool] + + ix_volume_config: NotRequired[IxStorageIxVolumeConfig] + host_path_config: NotRequired[IxStorageHostPathConfig] + tmpfs_config: NotRequired[IxStorageTmpfsConfig] + volume_config: NotRequired[IxStorageVolumeConfig] + nfs_config: NotRequired[IxStorageNfsConfig] + cifs_config: NotRequired[IxStorageCifsConfig] + + +class Storage: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._volume_mounts: set[VolumeMount] = set() + + def add(self, mount_path: str, config: "IxStorage"): + mount_path = valid_fs_path_or_raise(mount_path) + if mount_path in [m.mount_path for m in self._volume_mounts]: + raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") + + volume_mount = VolumeMount(self._render_instance, mount_path, config) + self._volume_mounts.add(volume_mount) + + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def has_mounts(self) -> bool: + return bool(self._volume_mounts) + + def render(self): + return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/sysctls.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/__init__.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/__init__.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/__init__.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_build_image.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_build_image.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_configs.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_configs.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_container.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_depends.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_depends.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_deps.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_device.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_dns.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_dns.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_environment.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_formatter.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_formatter.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_functions.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_functions.py new file mode 100644 index 0000000000..0ea3b57d18 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_functions.py @@ -0,0 +1,88 @@ +import re +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + tests = [ + {"func": "auto_cast", "values": ["1"], "expected": 1}, + {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, + {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, + { + "func": "bcrypt_hash", + "values": ["my_pass"], + "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, + {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, + {"func": "fail", "values": ["my_message"], "expect_raise": True}, + { + "func": "htpasswd", + "values": ["my_user", "my_pass"], + "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "is_boolean", "values": ["true"], "expected": True}, + {"func": "is_boolean", "values": ["false"], "expected": True}, + {"func": "is_number", "values": ["1"], "expected": True}, + {"func": "is_number", "values": ["1.1"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, + {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, + {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, + {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, + {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, + ] + + for test in tests: + print(test["func"], test) + func = render.funcs[test["func"]] + if test.get("expect_raise", False): + with pytest.raises(Exception): + func(*test["values"]) + elif test.get("expect_regex"): + r = func(*test["values"]) + assert re.match(test["expect_regex"], r) is not None + else: + r = func(*test["values"]) + assert r == test["expected"] diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_healthcheck.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_labels.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_labels.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_notes.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_notes.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_portal.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_portal.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_ports.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_ports.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_render.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_render.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_render.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_resources.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_resources.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_restart.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/tests/test_restart.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_sysctls.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_volumes.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_volumes.py new file mode 100644 index 0000000000..aef0d39481 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/tests/test_volumes.py @@ -0,0 +1,666 @@ +import pytest + + +from render import Render +from formatter import get_hashed_name_for_volume + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_volume_invalid_type(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "invalid_type"}) + + +def test_add_volume_empty_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("", {"type": "tmpfs"}) + + +def test_add_volume_duplicate_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_storage("/some/path", {"type": "tmpfs"}) + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "tmpfs"}) + + +def test_add_volume_host_path_invalid_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_host_path_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path"} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_with_acl_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_mount(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_acl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, + } + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test/acl", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "slave"}, + } + ] + + +def test_add_host_path_volume_mount_with_create_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_invalid_dataset_name(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_no_ix_volume_config(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume"} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_volume_mount(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_volume_mount_with_options(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = { + "type": "ix_volume", + "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, + } + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rslave"}, + } + ] + + +def test_cifs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_username(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_password(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_without_cifs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["verbose=true", "verbose=true"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["user=username"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": {"verbose": True}, + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": [{"verbose": True}], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_add_cifs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_cifs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["vers=3.0", "verbose=true"], + } + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "cifs", + "device": "//server/path", + "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_without_nfs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = { + "type": "nfs", + "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_add_nfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path"} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "nfs", + "device": ":/path", + "o": "addr=server,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_tmpfs_invalid_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_zero_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_invalid_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs"} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "tmpfs", + "target": "/some/path", + "read_only": False, + } + ] + + +def test_temporary_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "source": "test_temp_volume", + "type": "volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + + +def test_docker_volume_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume_missing_volume_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["volumes"] == {"test_volume": {}} + + +def test_anonymous_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} + ] + assert "volumes" not in output + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_not_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/some/path") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/validations.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_mount.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_mount.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_mount.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_mount_types.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_mount_types.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_sources.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_sources.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_sources.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_types.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volume_types.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volume_types.py diff --git a/ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volumes.py b/ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from ix-dev/stable/wg-easy/templates/library/base_v2_0_32/volumes.py rename to ix-dev/stable/wg-easy/templates/library/base_v2_1_0/volumes.py From c32b8e3e77c5f72bb040e0f7ba63cf8a5f5dbb6e Mon Sep 17 00:00:00 2001 From: sonicaj Date: Fri, 6 Dec 2024 15:12:45 +0000 Subject: [PATCH 2/3] Publish new changes in catalog [skip ci] --- .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ .../{1.0.15 => 1.0.16}/README.md | 0 .../{1.0.15 => 1.0.16}/app.yaml | 6 +- .../{1.0.15 => 1.0.16}/ix_values.yaml | 0 .../{1.0.15 => 1.0.16}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 0 .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 0 .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 0 .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 0 .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 0 .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0}/tests/test_deps.py | 105 ++- .../library/base_v2_1_0}/tests/test_device.py | 0 .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 0 .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 0 .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 0 .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/macros/haproxy_config.macro | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/cluster-values.yaml | 0 .../minio/{1.2.0 => 1.2.1}/README.md | 0 .../minio/{1.2.0 => 1.2.1}/app.yaml | 6 +- .../minio/{1.2.0 => 1.2.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../minio/{1.2.0 => 1.2.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 2 + .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 5 +- .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 36 + .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0}/tests/test_deps.py | 105 ++- .../library/base_v2_1_0}/tests/test_device.py | 10 + .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 8 + .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../test_values/basic-multi-mode-values.yaml | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/https-values.yaml | 0 .../syncthing/{1.1.0 => 1.1.1}/README.md | 0 .../syncthing/{1.1.0 => 1.1.1}/app.yaml | 6 +- .../syncthing/{1.1.0 => 1.1.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../syncthing/{1.1.0 => 1.1.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 2 + .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 5 +- .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 36 + .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0}/tests/test_deps.py | 105 ++- .../library/base_v2_1_0}/tests/test_device.py | 10 + .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 8 + .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/macros/setup.sh.jinja | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/https-values.yaml | 0 .../collabora/{1.2.1 => 1.2.2}/README.md | 0 .../collabora/{1.2.1 => 1.2.2}/app.yaml | 6 +- .../collabora/{1.2.1 => 1.2.2}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../collabora/{1.2.1 => 1.2.2}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py} | 214 +----- .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 2 + .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 5 +- .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 36 + .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0}/tests/test_deps.py | 105 ++- .../library/base_v2_1_0}/tests/test_device.py | 10 + .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 8 + .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/macros/nginx.conf.jinja | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/https-values.yaml | 0 .../library/base_v2_0_31/environment.py | 109 --- .../library/base_v2_0_31/tests/test_device.py | 121 ---- .../base_v2_0_31/tests/test_environment.py | 184 ----- .../diskoverdata/{1.4.1 => 1.4.2}/README.md | 0 .../diskoverdata/{1.4.1 => 1.4.2}/app.yaml | 6 +- .../{1.4.1 => 1.4.2}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../{1.4.1 => 1.4.2}/questions.yaml | 0 .../templates/diskover_macros/crontab | 0 .../templates/diskover_macros/setup-cron.sh | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0}/container.py | 30 +- .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0}/devices.py | 2 + .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0}/environment.py | 5 +- .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0}/healthcheck.py | 10 + .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0}/tests/test_container.py | 36 + .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0}/tests/test_device.py | 10 + .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0}/tests/test_environment.py | 12 + .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0}/tests/test_healthcheck.py | 8 + .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0}/validations.py | 9 +- .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../elastic-search/{1.2.0 => 1.2.1}/README.md | 0 .../elastic-search/{1.2.0 => 1.2.1}/app.yaml | 6 +- .../{1.2.0 => 1.2.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../{1.2.0 => 1.2.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/https-values.yaml | 0 .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ trains/stable/emby/{1.2.3 => 1.2.4}/README.md | 0 trains/stable/emby/{1.2.3 => 1.2.4}/app.yaml | 6 +- .../emby/{1.2.3 => 1.2.4}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../emby/{1.2.3 => 1.2.4}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/hostnet-values.yaml | 0 .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ .../home-assistant/{1.3.4 => 1.3.5}/README.md | 0 .../home-assistant/{1.3.4 => 1.3.5}/app.yaml | 6 +- .../{1.3.4 => 1.3.5}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../{1.3.4 => 1.3.5}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/macros/config.sh.jinja | 0 .../templates/macros/config.yaml.jinja | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/library/base_v2_0_34/deps.py | 454 ------------ .../library/base_v2_0_34/tests/test_deps.py | 380 ---------- .../stable/ix-app/{1.1.1 => 1.1.2}/README.md | 0 .../stable/ix-app/{1.1.1 => 1.1.2}/app.yaml | 6 +- .../ix-app/{1.1.1 => 1.1.2}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../ix-app/{1.1.1 => 1.1.2}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/functions.py | 111 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_21/validations.py | 203 ------ .../stable/minio/{1.2.1 => 1.2.2}/README.md | 0 trains/stable/minio/{1.2.1 => 1.2.2}/app.yaml | 6 +- .../minio/{1.2.1 => 1.2.2}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../minio/{1.2.1 => 1.2.2}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/https-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../stable/netdata/{1.2.0 => 1.2.1}/README.md | 0 .../stable/netdata/{1.2.0 => 1.2.1}/app.yaml | 6 +- .../netdata/{1.2.0 => 1.2.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../netdata/{1.2.0 => 1.2.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/functions.py | 111 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../templates/library/base_v2_0_21/storage.py | 106 --- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_functions.py | 65 -- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../base_v2_0_21/tests/test_volumes.py | 666 ------------------ .../library/base_v2_0_21/validations.py | 203 ------ .../nextcloud/{1.4.15 => 1.4.16}/README.md | 0 .../nextcloud/{1.4.15 => 1.4.16}/app.yaml | 6 +- .../{1.4.15 => 1.4.16}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../{1.4.15 => 1.4.16}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 0 .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/macros/nc.jinja.conf | 0 .../templates/macros/nc.jinja.sh | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/https-values.yaml | 0 .../templates/test_values/no-cron-values.yaml | 0 .../test_values/same-vol-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../photoprism/{1.2.0 => 1.2.1}/README.md | 0 .../photoprism/{1.2.0 => 1.2.1}/app.yaml | 6 +- .../{1.2.0 => 1.2.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../{1.2.0 => 1.2.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 3 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 0 .../templates/library/base_v2_1_0}/sysctls.py | 0 .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 0 .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../base_v2_1_0}/tests/test_sysctls.py | 0 .../base_v2_1_0}/tests/test_volumes.py | 0 .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/host-values.yaml | 0 .../templates/test_values/https-values.yaml | 0 .../templates/test_values/pass-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../stable/pihole/{1.2.0 => 1.2.1}/README.md | 0 .../stable/pihole/{1.2.0 => 1.2.1}/app.yaml | 6 +- .../pihole/{1.2.0 => 1.2.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../pihole/{1.2.0 => 1.2.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 42 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/dhcp-values.yaml | 0 .../library/base_v2_0_21/container.py | 300 -------- .../templates/library/base_v2_0_21/deps.py | 443 ------------ .../templates/library/base_v2_0_21/devices.py | 63 -- .../library/base_v2_0_21/environment.py | 109 --- .../library/base_v2_0_21/functions.py | 111 --- .../library/base_v2_0_21/healthcheck.py | 193 ----- .../templates/library/base_v2_0_21/storage.py | 106 --- .../base_v2_0_21/tests/test_container.py | 273 ------- .../library/base_v2_0_21/tests/test_deps.py | 380 ---------- .../library/base_v2_0_21/tests/test_device.py | 121 ---- .../base_v2_0_21/tests/test_environment.py | 184 ----- .../base_v2_0_21/tests/test_functions.py | 65 -- .../base_v2_0_21/tests/test_healthcheck.py | 187 ----- .../base_v2_0_21/tests/test_volumes.py | 666 ------------------ .../library/base_v2_0_21/validations.py | 203 ------ trains/stable/plex/{1.1.4 => 1.1.5}/README.md | 0 trains/stable/plex/{1.1.4 => 1.1.5}/app.yaml | 6 +- .../plex/{1.1.4 => 1.1.5}/ix_values.yaml | 0 .../{1.1.4 => 1.1.5}/migrations/__init__.py | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../plex/{1.1.4 => 1.1.5}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 42 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/hostnet-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../prometheus/{1.2.0 => 1.2.1}/README.md | 0 .../prometheus/{1.2.0 => 1.2.1}/app.yaml | 6 +- .../{1.2.0 => 1.2.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../{1.2.0 => 1.2.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0}/functions.py | 42 +- .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../{1.2.0 => 1.2.1}/templates/macros/init.sh | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/hostnet-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../stable/storj/{1.2.0 => 1.2.1}/README.md | 0 trains/stable/storj/{1.2.0 => 1.2.1}/app.yaml | 6 +- .../storj/{1.2.0 => 1.2.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../storj/{1.2.0 => 1.2.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0/functions.py | 149 ++++ .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0}/storage.py | 12 +- .../templates/library/base_v2_1_0/sysctls.py | 38 + .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0}/tests/test_functions.py | 23 + .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../base_v2_1_0}/tests/test_volumes.py | 6 +- .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/macros/entrypoint.sh | 0 .../{1.2.0 => 1.2.1}/templates/macros/init.sh | 0 .../templates/test_values/basic-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../syncthing/{1.1.0 => 1.1.1}/README.md | 0 .../syncthing/{1.1.0 => 1.1.1}/app.yaml | 6 +- .../syncthing/{1.1.0 => 1.1.1}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../syncthing/{1.1.0 => 1.1.1}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0/functions.py | 149 ++++ .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0/storage.py | 116 +++ .../templates/library/base_v2_1_0/sysctls.py | 38 + .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0/tests/test_functions.py | 88 +++ .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../library/base_v2_1_0/tests/test_volumes.py | 666 ++++++++++++++++++ .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/host-values.yaml | 0 .../library/base_v2_0_32/container.py | 317 --------- .../templates/library/base_v2_0_32/deps.py | 454 ------------ .../templates/library/base_v2_0_32/devices.py | 66 -- .../library/base_v2_0_32/environment.py | 109 --- .../library/base_v2_0_32/healthcheck.py | 193 ----- .../base_v2_0_32/tests/test_container.py | 324 --------- .../library/base_v2_0_32/tests/test_deps.py | 380 ---------- .../library/base_v2_0_32/tests/test_device.py | 121 ---- .../base_v2_0_32/tests/test_environment.py | 184 ----- .../base_v2_0_32/tests/test_healthcheck.py | 187 ----- .../library/base_v2_0_32/validations.py | 227 ------ .../stable/wg-easy/{1.1.1 => 1.1.2}/README.md | 0 .../stable/wg-easy/{1.1.1 => 1.1.2}/app.yaml | 6 +- .../wg-easy/{1.1.1 => 1.1.2}/ix_values.yaml | 0 .../migrations/migrate_from_kubernetes | 0 .../migrations/migration_helpers/__init__.py | 0 .../migrations/migration_helpers/cpu.py | 0 .../migration_helpers/dns_config.py | 0 .../migration_helpers/kubernetes_secrets.py | 0 .../migrations/migration_helpers/memory.py | 0 .../migrations/migration_helpers/resources.py | 0 .../migrations/migration_helpers/storage.py | 0 .../wg-easy/{1.1.1 => 1.1.2}/questions.yaml | 0 .../templates/docker-compose.yaml | 0 .../library/base_v2_1_0}/__init__.py | 0 .../templates/library/base_v2_1_0}/configs.py | 0 .../library/base_v2_1_0/container.py | 339 +++++++++ .../templates/library/base_v2_1_0}/depends.py | 0 .../templates/library/base_v2_1_0}/deploy.py | 0 .../templates/library/base_v2_1_0/deps.py | 32 + .../library/base_v2_1_0/deps_mariadb.py | 65 ++ .../library/base_v2_1_0/deps_perms.py | 252 +++++++ .../library/base_v2_1_0/deps_postgres.py | 279 ++++++++ .../library/base_v2_1_0/deps_redis.py | 71 ++ .../templates/library/base_v2_1_0}/device.py | 0 .../templates/library/base_v2_1_0/devices.py | 68 ++ .../templates/library/base_v2_1_0}/dns.py | 0 .../library/base_v2_1_0/environment.py | 112 +++ .../templates/library/base_v2_1_0}/error.py | 0 .../library/base_v2_1_0}/formatter.py | 0 .../library/base_v2_1_0/functions.py | 149 ++++ .../library/base_v2_1_0/healthcheck.py | 203 ++++++ .../templates/library/base_v2_1_0}/labels.py | 0 .../templates/library/base_v2_1_0}/notes.py | 0 .../templates/library/base_v2_1_0}/portal.py | 0 .../templates/library/base_v2_1_0}/portals.py | 0 .../templates/library/base_v2_1_0}/ports.py | 0 .../templates/library/base_v2_1_0}/render.py | 0 .../library/base_v2_1_0}/resources.py | 0 .../templates/library/base_v2_1_0}/restart.py | 0 .../templates/library/base_v2_1_0/storage.py | 116 +++ .../templates/library/base_v2_1_0/sysctls.py | 38 + .../library/base_v2_1_0}/tests/__init__.py | 0 .../base_v2_1_0}/tests/test_build_image.py | 0 .../base_v2_1_0}/tests/test_configs.py | 0 .../base_v2_1_0/tests/test_container.py | 360 ++++++++++ .../base_v2_1_0}/tests/test_depends.py | 0 .../library/base_v2_1_0/tests/test_deps.py | 477 +++++++++++++ .../library/base_v2_1_0/tests/test_device.py | 131 ++++ .../library/base_v2_1_0}/tests/test_dns.py | 0 .../base_v2_1_0/tests/test_environment.py | 196 ++++++ .../base_v2_1_0}/tests/test_formatter.py | 0 .../base_v2_1_0/tests/test_functions.py | 88 +++ .../base_v2_1_0/tests/test_healthcheck.py | 195 +++++ .../library/base_v2_1_0}/tests/test_labels.py | 0 .../library/base_v2_1_0}/tests/test_notes.py | 0 .../library/base_v2_1_0}/tests/test_portal.py | 0 .../library/base_v2_1_0}/tests/test_ports.py | 0 .../library/base_v2_1_0}/tests/test_render.py | 0 .../base_v2_1_0}/tests/test_resources.py | 0 .../base_v2_1_0}/tests/test_restart.py | 0 .../library/base_v2_1_0/tests/test_sysctls.py | 62 ++ .../library/base_v2_1_0/tests/test_volumes.py | 666 ++++++++++++++++++ .../library/base_v2_1_0/validations.py | 234 ++++++ .../library/base_v2_1_0}/volume_mount.py | 0 .../base_v2_1_0}/volume_mount_types.py | 0 .../library/base_v2_1_0}/volume_sources.py | 0 .../library/base_v2_1_0}/volume_types.py | 0 .../templates/library/base_v2_1_0}/volumes.py | 0 .../templates/test_values/basic-values.yaml | 0 .../templates/test_values/hostnet-values.yaml | 0 1500 files changed, 49166 insertions(+), 39025 deletions(-) delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/container.py delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/deps.py delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/devices.py delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/validations.py rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/README.md (100%) rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/app.yaml (92%) rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/ix_values.yaml (100%) rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/questions.yaml (100%) rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/templates/docker-compose.yaml (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/configs.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/container.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/depends.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps.py create mode 100644 trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_mariadb.py rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32/deps.py => asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_redis.py rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/device.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/devices.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/dns.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/environment.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/error.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/functions.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/healthcheck.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/labels.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/notes.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/portal.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/portals.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/ports.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/render.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/resources.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/restart.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/storage.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_configs.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_container.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_depends.py (100%) rename trains/{stable/diskoverdata/1.4.1/templates/library/base_v2_0_31 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_deps.py (80%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_device.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_dns.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_environment.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_healthcheck.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename trains/{stable/ix-app/1.1.1/templates/library/base_v2_0_34 => enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0}/validations.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15/templates/library/base_v2_0_21 => 1.0.16/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/templates/macros/haproxy_config.macro (100%) rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/templates/test_values/basic-values.yaml (100%) rename trains/enterprise/asigra-ds-system/{1.0.15 => 1.0.16}/templates/test_values/cluster-values.yaml (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/README.md (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/app.yaml (86%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/ix_values.yaml (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migrate_from_kubernetes (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migration_helpers/__init__.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migration_helpers/cpu.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migration_helpers/memory.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migration_helpers/resources.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/migrations/migration_helpers/storage.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/questions.yaml (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/templates/docker-compose.yaml (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/configs.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/container.py (93%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32/deps.py => enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_redis.py rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/device.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/devices.py (93%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/dns.py (100%) rename trains/enterprise/{asigra-ds-system/1.0.15/templates/library/base_v2_0_21 => minio/1.2.1/templates/library/base_v2_1_0}/environment.py (95%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/functions.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/healthcheck.py (95%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/storage.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/tests/test_container.py (89%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/minio/1.2.1/templates/library/base_v2_1_0}/tests/test_deps.py (80%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_device.py (89%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) rename trains/enterprise/{asigra-ds-system/1.0.15/templates/library/base_v2_0_21 => minio/1.2.1/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/minio/1.2.1/templates/library/base_v2_1_0}/tests/test_healthcheck.py (95%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename trains/enterprise/{syncthing/1.1.0/templates/library/base_v2_0_32 => minio/1.2.1/templates/library/base_v2_1_0}/validations.py (94%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/enterprise/minio/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/templates/test_values/basic-multi-mode-values.yaml (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/templates/test_values/basic-values.yaml (100%) rename trains/enterprise/minio/{1.2.0 => 1.2.1}/templates/test_values/https-values.yaml (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/README.md (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/app.yaml (93%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/ix_values.yaml (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migrate_from_kubernetes (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/__init__.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/cpu.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/memory.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/resources.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/storage.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/questions.yaml (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/templates/docker-compose.yaml (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/configs.py (100%) rename trains/{stable/diskoverdata/1.4.1/templates/library/base_v2_0_31 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/container.py (93%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py rename trains/{stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/deps.py => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/device.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/devices.py (93%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/dns.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => syncthing/1.1.1/templates/library/base_v2_1_0}/environment.py (95%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/functions.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/healthcheck.py (95%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/storage.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/tests/test_container.py (89%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => syncthing/1.1.1/templates/library/base_v2_1_0}/tests/test_deps.py (80%) rename trains/enterprise/{asigra-ds-system/1.0.15/templates/library/base_v2_0_21 => syncthing/1.1.1/templates/library/base_v2_1_0}/tests/test_device.py (89%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => syncthing/1.1.1/templates/library/base_v2_1_0}/tests/test_healthcheck.py (95%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/{stable/collabora/1.2.1/templates/library/base_v2_0_32 => enterprise/syncthing/1.1.1/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename trains/enterprise/{minio/1.2.0/templates/library/base_v2_0_32 => syncthing/1.1.1/templates/library/base_v2_1_0}/validations.py (94%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/enterprise/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/templates/macros/setup.sh.jinja (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/templates/test_values/basic-values.yaml (100%) rename trains/enterprise/syncthing/{1.1.0 => 1.1.1}/templates/test_values/https-values.yaml (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/README.md (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/app.yaml (92%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/ix_values.yaml (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migrate_from_kubernetes (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migration_helpers/memory.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migration_helpers/resources.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/migrations/migration_helpers/storage.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/questions.yaml (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/templates/docker-compose.yaml (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/configs.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/container.py (93%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py rename trains/{enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py => stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_perms.py} (56%) create mode 100644 trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/device.py (100%) rename trains/{enterprise/syncthing/1.1.0/templates/library/base_v2_0_32 => stable/collabora/1.2.2/templates/library/base_v2_1_0}/devices.py (93%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/dns.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/environment.py (95%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{elastic-search/1.2.0/templates/library/base_v2_0_32 => collabora/1.2.2/templates/library/base_v2_1_0}/functions.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => collabora/1.2.2/templates/library/base_v2_1_0}/healthcheck.py (95%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => collabora/1.2.2/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => collabora/1.2.2/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_configs.py (100%) rename trains/{enterprise/minio/1.2.0/templates/library/base_v2_0_32 => stable/collabora/1.2.2/templates/library/base_v2_1_0}/tests/test_container.py (89%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_depends.py (100%) rename trains/{enterprise/syncthing/1.1.0/templates/library/base_v2_0_32 => stable/collabora/1.2.2/templates/library/base_v2_1_0}/tests/test_deps.py (80%) rename trains/{enterprise/syncthing/1.1.0/templates/library/base_v2_0_32 => stable/collabora/1.2.2/templates/library/base_v2_1_0}/tests/test_device.py (89%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_dns.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => collabora/1.2.2/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => collabora/1.2.2/templates/library/base_v2_1_0}/tests/test_healthcheck.py (95%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => collabora/1.2.2/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => collabora/1.2.2/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/validations.py (94%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/collabora/{1.2.1/templates/library/base_v2_0_32 => 1.2.2/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/templates/macros/nginx.conf.jinja (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/templates/test_values/basic-values.yaml (100%) rename trains/stable/collabora/{1.2.1 => 1.2.2}/templates/test_values/https-values.yaml (100%) delete mode 100644 trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/environment.py delete mode 100644 trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_device.py delete mode 100644 trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_environment.py rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/README.md (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/app.yaml (92%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/ix_values.yaml (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migrate_from_kubernetes (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migration_helpers/memory.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migration_helpers/resources.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/migrations/migration_helpers/storage.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/questions.yaml (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/templates/diskover_macros/crontab (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/templates/diskover_macros/setup-cron.sh (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/templates/docker-compose.yaml (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/configs.py (100%) rename trains/{enterprise/minio/1.2.0/templates/library/base_v2_0_32 => stable/diskoverdata/1.4.2/templates/library/base_v2_1_0}/container.py (93%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/device.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/devices.py (93%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/dns.py (100%) rename trains/{enterprise/syncthing/1.1.0/templates/library/base_v2_0_32 => stable/diskoverdata/1.4.2/templates/library/base_v2_1_0}/environment.py (95%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{ix-app/1.1.1/templates/library/base_v2_0_34 => diskoverdata/1.4.2/templates/library/base_v2_1_0}/functions.py (100%) rename trains/{enterprise/minio/1.2.0/templates/library/base_v2_0_32 => stable/diskoverdata/1.4.2/templates/library/base_v2_1_0}/healthcheck.py (95%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{elastic-search/1.2.0/templates/library/base_v2_0_32 => diskoverdata/1.4.2/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{elastic-search/1.2.0/templates/library/base_v2_0_32 => diskoverdata/1.4.2/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_configs.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_container.py (89%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_deps.py rename trains/stable/{collabora/1.2.1/templates/library/base_v2_0_32 => diskoverdata/1.4.2/templates/library/base_v2_1_0}/tests/test_device.py (89%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_dns.py (100%) rename trains/{enterprise/minio/1.2.0/templates/library/base_v2_0_32 => stable/diskoverdata/1.4.2/templates/library/base_v2_1_0}/tests/test_environment.py (93%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{elastic-search/1.2.0/templates/library/base_v2_0_32 => diskoverdata/1.4.2/templates/library/base_v2_1_0}/tests/test_functions.py (100%) rename trains/{enterprise/syncthing/1.1.0/templates/library/base_v2_0_32 => stable/diskoverdata/1.4.2/templates/library/base_v2_1_0}/tests/test_healthcheck.py (95%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{elastic-search/1.2.0/templates/library/base_v2_0_32 => diskoverdata/1.4.2/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{elastic-search/1.2.0/templates/library/base_v2_0_32 => diskoverdata/1.4.2/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/validations.py (94%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/diskoverdata/{1.4.1/templates/library/base_v2_0_31 => 1.4.2/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/diskoverdata/{1.4.1 => 1.4.2}/templates/test_values/basic-values.yaml (100%) delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/validations.py rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/README.md (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/app.yaml (86%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/ix_values.yaml (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migrate_from_kubernetes (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migration_helpers/memory.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migration_helpers/resources.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/migrations/migration_helpers/storage.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/questions.yaml (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/templates/docker-compose.yaml (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/container.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/devices.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/environment.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{netdata/1.2.0/templates/library/base_v2_0_32 => elastic-search/1.2.1/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{ix-app/1.1.1/templates/library/base_v2_0_34 => elastic-search/1.2.1/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{ix-app/1.1.1/templates/library/base_v2_0_34 => elastic-search/1.2.1/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{ix-app/1.1.1/templates/library/base_v2_0_34 => elastic-search/1.2.1/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{ix-app/1.1.1/templates/library/base_v2_0_34 => elastic-search/1.2.1/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{ix-app/1.1.1/templates/library/base_v2_0_34 => elastic-search/1.2.1/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/validations.py rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/elastic-search/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/templates/test_values/basic-values.yaml (100%) rename trains/stable/elastic-search/{1.2.0 => 1.2.1}/templates/test_values/https-values.yaml (100%) delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/container.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/deps.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/devices.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/environment.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 trains/stable/emby/1.2.3/templates/library/base_v2_0_21/validations.py rename trains/stable/emby/{1.2.3 => 1.2.4}/README.md (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/app.yaml (91%) rename trains/stable/emby/{1.2.3 => 1.2.4}/ix_values.yaml (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migrate_from_kubernetes (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migration_helpers/memory.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migration_helpers/resources.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/migrations/migration_helpers/storage.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/questions.yaml (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/templates/docker-compose.yaml (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/container.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/devices.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/environment.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{photoprism/1.2.0/templates/library/base_v2_0_32 => emby/1.2.4/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{netdata/1.2.0/templates/library/base_v2_0_32 => emby/1.2.4/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{netdata/1.2.0/templates/library/base_v2_0_32 => emby/1.2.4/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{netdata/1.2.0/templates/library/base_v2_0_32 => emby/1.2.4/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{netdata/1.2.0/templates/library/base_v2_0_32 => emby/1.2.4/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{netdata/1.2.0/templates/library/base_v2_0_32 => emby/1.2.4/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/emby/1.2.4/templates/library/base_v2_1_0/validations.py rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/emby/{1.2.3/templates/library/base_v2_0_21 => 1.2.4/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/templates/test_values/basic-values.yaml (100%) rename trains/stable/emby/{1.2.3 => 1.2.4}/templates/test_values/hostnet-values.yaml (100%) delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/container.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/deps.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/devices.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/environment.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/validations.py rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/README.md (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/app.yaml (91%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/ix_values.yaml (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migrate_from_kubernetes (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migration_helpers/memory.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migration_helpers/resources.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/migrations/migration_helpers/storage.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/questions.yaml (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/templates/docker-compose.yaml (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/container.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/devices.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/environment.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{pihole/1.2.0/templates/library/base_v2_0_32 => home-assistant/1.3.5/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{photoprism/1.2.0/templates/library/base_v2_0_32 => home-assistant/1.3.5/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{photoprism/1.2.0/templates/library/base_v2_0_32 => home-assistant/1.3.5/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{photoprism/1.2.0/templates/library/base_v2_0_32 => home-assistant/1.3.5/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{photoprism/1.2.0/templates/library/base_v2_0_32 => home-assistant/1.3.5/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{photoprism/1.2.0/templates/library/base_v2_0_32 => home-assistant/1.3.5/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/validations.py rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/home-assistant/{1.3.4/templates/library/base_v2_0_21 => 1.3.5/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/templates/macros/config.sh.jinja (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/templates/macros/config.yaml.jinja (100%) rename trains/stable/home-assistant/{1.3.4 => 1.3.5}/templates/test_values/basic-values.yaml (100%) delete mode 100644 trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/deps.py delete mode 100644 trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_deps.py rename trains/stable/ix-app/{1.1.1 => 1.1.2}/README.md (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/app.yaml (78%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/ix_values.yaml (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migrate_from_kubernetes (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migration_helpers/memory.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migration_helpers/resources.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/migrations/migration_helpers/storage.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/questions.yaml (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/templates/docker-compose.yaml (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/container.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/devices.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/environment.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{prometheus/1.2.0/templates/library/base_v2_0_32 => ix-app/1.1.2/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{pihole/1.2.0/templates/library/base_v2_0_32 => ix-app/1.1.2/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{pihole/1.2.0/templates/library/base_v2_0_32 => ix-app/1.1.2/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{pihole/1.2.0/templates/library/base_v2_0_32 => ix-app/1.1.2/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{pihole/1.2.0/templates/library/base_v2_0_32 => ix-app/1.1.2/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{pihole/1.2.0/templates/library/base_v2_0_32 => ix-app/1.1.2/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/validations.py rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/ix-app/{1.1.1/templates/library/base_v2_0_34 => 1.1.2/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/ix-app/{1.1.1 => 1.1.2}/templates/test_values/basic-values.yaml (100%) delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/container.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/deps.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/devices.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/environment.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/functions.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 trains/stable/minio/1.2.1/templates/library/base_v2_0_21/validations.py rename trains/stable/minio/{1.2.1 => 1.2.2}/README.md (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/app.yaml (87%) rename trains/stable/minio/{1.2.1 => 1.2.2}/ix_values.yaml (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migrate_from_kubernetes (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migration_helpers/memory.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migration_helpers/resources.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/migrations/migration_helpers/storage.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/questions.yaml (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/templates/docker-compose.yaml (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/container.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/devices.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/environment.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{storj/1.2.0/templates/library/base_v2_0_32 => minio/1.2.2/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{prometheus/1.2.0/templates/library/base_v2_0_32 => minio/1.2.2/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{prometheus/1.2.0/templates/library/base_v2_0_32 => minio/1.2.2/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{prometheus/1.2.0/templates/library/base_v2_0_32 => minio/1.2.2/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{prometheus/1.2.0/templates/library/base_v2_0_32 => minio/1.2.2/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{prometheus/1.2.0/templates/library/base_v2_0_32 => minio/1.2.2/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/minio/1.2.2/templates/library/base_v2_1_0/validations.py rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/minio/{1.2.1/templates/library/base_v2_0_21 => 1.2.2/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/templates/test_values/basic-values.yaml (100%) rename trains/stable/minio/{1.2.1 => 1.2.2}/templates/test_values/https-values.yaml (100%) delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/validations.py rename trains/stable/netdata/{1.2.0 => 1.2.1}/README.md (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/app.yaml (94%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/ix_values.yaml (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migrate_from_kubernetes (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migration_helpers/memory.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migration_helpers/resources.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/migrations/migration_helpers/storage.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/questions.yaml (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/templates/docker-compose.yaml (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/container.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/devices.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/environment.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{syncthing/1.1.0/templates/library/base_v2_0_32 => netdata/1.2.1/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{storj/1.2.0/templates/library/base_v2_0_32 => netdata/1.2.1/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{storj/1.2.0/templates/library/base_v2_0_32 => netdata/1.2.1/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{storj/1.2.0/templates/library/base_v2_0_32 => netdata/1.2.1/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{storj/1.2.0/templates/library/base_v2_0_32 => netdata/1.2.1/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{storj/1.2.0/templates/library/base_v2_0_32 => netdata/1.2.1/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/validations.py rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/netdata/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/netdata/{1.2.0 => 1.2.1}/templates/test_values/basic-values.yaml (100%) delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/container.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/deps.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/devices.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/environment.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/functions.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/storage.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_functions.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_volumes.py delete mode 100644 trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/validations.py rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/README.md (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/app.yaml (94%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/ix_values.yaml (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migrate_from_kubernetes (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migration_helpers/memory.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migration_helpers/resources.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/migrations/migration_helpers/storage.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/questions.yaml (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/templates/docker-compose.yaml (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/container.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/devices.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/environment.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{wg-easy/1.1.1/templates/library/base_v2_0_32 => nextcloud/1.4.16/templates/library/base_v2_1_0}/functions.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{syncthing/1.1.0/templates/library/base_v2_0_32 => nextcloud/1.4.16/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{syncthing/1.1.0/templates/library/base_v2_0_32 => nextcloud/1.4.16/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{syncthing/1.1.0/templates/library/base_v2_0_32 => nextcloud/1.4.16/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{syncthing/1.1.0/templates/library/base_v2_0_32 => nextcloud/1.4.16/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{syncthing/1.1.0/templates/library/base_v2_0_32 => nextcloud/1.4.16/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/validations.py rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/nextcloud/{1.4.15/templates/library/base_v2_0_21 => 1.4.16/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/templates/macros/nc.jinja.conf (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/templates/macros/nc.jinja.sh (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/templates/test_values/basic-values.yaml (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/templates/test_values/https-values.yaml (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/templates/test_values/no-cron-values.yaml (100%) rename trains/stable/nextcloud/{1.4.15 => 1.4.16}/templates/test_values/same-vol-values.yaml (100%) delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/validations.py rename trains/stable/photoprism/{1.2.0 => 1.2.1}/README.md (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/app.yaml (91%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/ix_values.yaml (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migrate_from_kubernetes (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migration_helpers/memory.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migration_helpers/resources.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/migrations/migration_helpers/storage.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/questions.yaml (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/templates/docker-compose.yaml (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/container.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/devices.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/environment.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{diskoverdata/1.4.1/templates/library/base_v2_0_31 => photoprism/1.2.1/templates/library/base_v2_1_0}/functions.py (99%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{wg-easy/1.1.1/templates/library/base_v2_0_32 => photoprism/1.2.1/templates/library/base_v2_1_0}/storage.py (100%) rename trains/stable/{wg-easy/1.1.1/templates/library/base_v2_0_32 => photoprism/1.2.1/templates/library/base_v2_1_0}/sysctls.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{wg-easy/1.1.1/templates/library/base_v2_0_32 => photoprism/1.2.1/templates/library/base_v2_1_0}/tests/test_functions.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) rename trains/stable/{wg-easy/1.1.1/templates/library/base_v2_0_32 => photoprism/1.2.1/templates/library/base_v2_1_0}/tests/test_sysctls.py (100%) rename trains/stable/{wg-easy/1.1.1/templates/library/base_v2_0_32 => photoprism/1.2.1/templates/library/base_v2_1_0}/tests/test_volumes.py (100%) create mode 100644 trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/validations.py rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/photoprism/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/templates/test_values/basic-values.yaml (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/templates/test_values/host-values.yaml (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/templates/test_values/https-values.yaml (100%) rename trains/stable/photoprism/{1.2.0 => 1.2.1}/templates/test_values/pass-values.yaml (100%) delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/validations.py rename trains/stable/pihole/{1.2.0 => 1.2.1}/README.md (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/app.yaml (93%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/ix_values.yaml (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migrate_from_kubernetes (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migration_helpers/memory.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migration_helpers/resources.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/migrations/migration_helpers/storage.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/questions.yaml (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/templates/docker-compose.yaml (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/container.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/devices.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/environment.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/{enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21 => stable/pihole/1.2.1/templates/library/base_v2_1_0}/functions.py (63%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{home-assistant/1.3.4/templates/library/base_v2_0_21 => pihole/1.2.1/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/sysctls.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{emby/1.2.3/templates/library/base_v2_0_21 => pihole/1.2.1/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py rename trains/stable/{emby/1.2.3/templates/library/base_v2_0_21 => pihole/1.2.1/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/validations.py rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/pihole/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/templates/test_values/basic-values.yaml (100%) rename trains/stable/pihole/{1.2.0 => 1.2.1}/templates/test_values/dhcp-values.yaml (100%) delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/container.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/deps.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/devices.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/environment.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/functions.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/healthcheck.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/storage.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_container.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_deps.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_device.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_environment.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_functions.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_healthcheck.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_volumes.py delete mode 100644 trains/stable/plex/1.1.4/templates/library/base_v2_0_21/validations.py rename trains/stable/plex/{1.1.4 => 1.1.5}/README.md (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/app.yaml (91%) rename trains/stable/plex/{1.1.4 => 1.1.5}/ix_values.yaml (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/__init__.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migrate_from_kubernetes (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migration_helpers/memory.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migration_helpers/resources.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/migrations/migration_helpers/storage.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/questions.yaml (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/templates/docker-compose.yaml (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/container.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/devices.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/environment.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{emby/1.2.3/templates/library/base_v2_0_21 => plex/1.1.5/templates/library/base_v2_1_0}/functions.py (63%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{minio/1.2.1/templates/library/base_v2_0_21 => plex/1.1.5/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/sysctls.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/{enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21 => stable/plex/1.1.5/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_sysctls.py rename trains/{enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21 => stable/plex/1.1.5/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 trains/stable/plex/1.1.5/templates/library/base_v2_1_0/validations.py rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/plex/{1.1.4/templates/library/base_v2_0_21 => 1.1.5/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/templates/test_values/basic-values.yaml (100%) rename trains/stable/plex/{1.1.4 => 1.1.5}/templates/test_values/hostnet-values.yaml (100%) delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/validations.py rename trains/stable/prometheus/{1.2.0 => 1.2.1}/README.md (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/app.yaml (86%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/ix_values.yaml (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migrate_from_kubernetes (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migration_helpers/memory.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migration_helpers/resources.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/migrations/migration_helpers/storage.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/questions.yaml (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/templates/docker-compose.yaml (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/container.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/devices.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/environment.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/formatter.py (100%) rename trains/stable/{home-assistant/1.3.4/templates/library/base_v2_0_21 => prometheus/1.2.1/templates/library/base_v2_1_0}/functions.py (63%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/{enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21 => stable/prometheus/1.2.1/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/sysctls.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{home-assistant/1.3.4/templates/library/base_v2_0_21 => prometheus/1.2.1/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py rename trains/stable/{home-assistant/1.3.4/templates/library/base_v2_0_21 => prometheus/1.2.1/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/validations.py rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/prometheus/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/templates/macros/init.sh (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/templates/test_values/basic-values.yaml (100%) rename trains/stable/prometheus/{1.2.0 => 1.2.1}/templates/test_values/hostnet-values.yaml (100%) delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/storj/1.2.0/templates/library/base_v2_0_32/validations.py rename trains/stable/storj/{1.2.0 => 1.2.1}/README.md (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/app.yaml (89%) rename trains/stable/storj/{1.2.0 => 1.2.1}/ix_values.yaml (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migrate_from_kubernetes (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migration_helpers/memory.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migration_helpers/resources.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/migrations/migration_helpers/storage.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/questions.yaml (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/templates/docker-compose.yaml (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/container.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/devices.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/environment.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/formatter.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/functions.py create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/restart.py (100%) rename trains/stable/{emby/1.2.3/templates/library/base_v2_0_21 => storj/1.2.1/templates/library/base_v2_1_0}/storage.py (87%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/sysctls.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) rename trains/stable/{minio/1.2.1/templates/library/base_v2_0_21 => storj/1.2.1/templates/library/base_v2_1_0}/tests/test_functions.py (68%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py rename trains/stable/{minio/1.2.1/templates/library/base_v2_0_21 => storj/1.2.1/templates/library/base_v2_1_0}/tests/test_volumes.py (99%) create mode 100644 trains/stable/storj/1.2.1/templates/library/base_v2_1_0/validations.py rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/storj/{1.2.0/templates/library/base_v2_0_32 => 1.2.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/templates/macros/entrypoint.sh (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/templates/macros/init.sh (100%) rename trains/stable/storj/{1.2.0 => 1.2.1}/templates/test_values/basic-values.yaml (100%) delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/validations.py rename trains/stable/syncthing/{1.1.0 => 1.1.1}/README.md (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/app.yaml (93%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/ix_values.yaml (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migrate_from_kubernetes (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/memory.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/resources.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/migrations/migration_helpers/storage.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/questions.yaml (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/templates/docker-compose.yaml (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/container.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/devices.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/environment.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/formatter.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/functions.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/restart.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/storage.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/sysctls.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_functions.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_sysctls.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_volumes.py create mode 100644 trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/validations.py rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/syncthing/{1.1.0/templates/library/base_v2_0_32 => 1.1.1/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/templates/test_values/basic-values.yaml (100%) rename trains/stable/syncthing/{1.1.0 => 1.1.1}/templates/test_values/host-values.yaml (100%) delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/container.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/deps.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/devices.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/environment.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/healthcheck.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_container.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_deps.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_device.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_environment.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_healthcheck.py delete mode 100644 trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/validations.py rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/README.md (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/app.yaml (88%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/ix_values.yaml (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migrate_from_kubernetes (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migration_helpers/__init__.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migration_helpers/cpu.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migration_helpers/dns_config.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migration_helpers/kubernetes_secrets.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migration_helpers/memory.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migration_helpers/resources.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/migrations/migration_helpers/storage.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/questions.yaml (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/templates/docker-compose.yaml (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/__init__.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/configs.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/container.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/depends.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/deploy.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_perms.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_postgres.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_redis.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/device.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/devices.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/dns.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/environment.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/error.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/formatter.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/functions.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/healthcheck.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/labels.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/notes.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/portal.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/portals.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/ports.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/render.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/resources.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/restart.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/storage.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/sysctls.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/__init__.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_build_image.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_configs.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_container.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_depends.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_device.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_dns.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_formatter.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_functions.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_labels.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_notes.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_portal.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_ports.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_render.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_resources.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/tests/test_restart.py (100%) create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_sysctls.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_volumes.py create mode 100644 trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/validations.py rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/volume_mount.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/volume_mount_types.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/volume_sources.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/volume_types.py (100%) rename trains/stable/wg-easy/{1.1.1/templates/library/base_v2_0_32 => 1.1.2/templates/library/base_v2_1_0}/volumes.py (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/templates/test_values/basic-values.yaml (100%) rename trains/stable/wg-easy/{1.1.1 => 1.1.2}/templates/test_values/hostnet-values.yaml (100%) diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/container.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/deps.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/devices.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/healthcheck.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_container.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_deps.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_healthcheck.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/validations.py b/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/enterprise/asigra-ds-system/1.0.15/README.md b/trains/enterprise/asigra-ds-system/1.0.16/README.md similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/README.md rename to trains/enterprise/asigra-ds-system/1.0.16/README.md diff --git a/trains/enterprise/asigra-ds-system/1.0.15/app.yaml b/trains/enterprise/asigra-ds-system/1.0.16/app.yaml similarity index 92% rename from trains/enterprise/asigra-ds-system/1.0.15/app.yaml rename to trains/enterprise/asigra-ds-system/1.0.16/app.yaml index 0247e36db1..ce47338fac 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/app.yaml +++ b/trains/enterprise/asigra-ds-system/1.0.16/app.yaml @@ -19,8 +19,8 @@ keywords: - backup - restore - asigra -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -47,4 +47,4 @@ sources: - https://hub.docker.com/r/asigra/ds-system title: Asigra DS-System train: enterprise -version: 1.0.15 +version: 1.0.16 diff --git a/trains/enterprise/asigra-ds-system/1.0.15/ix_values.yaml b/trains/enterprise/asigra-ds-system/1.0.16/ix_values.yaml similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/ix_values.yaml rename to trains/enterprise/asigra-ds-system/1.0.16/ix_values.yaml diff --git a/trains/enterprise/asigra-ds-system/1.0.15/questions.yaml b/trains/enterprise/asigra-ds-system/1.0.16/questions.yaml similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/questions.yaml rename to trains/enterprise/asigra-ds-system/1.0.16/questions.yaml diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/docker-compose.yaml b/trains/enterprise/asigra-ds-system/1.0.16/templates/docker-compose.yaml similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/docker-compose.yaml rename to trains/enterprise/asigra-ds-system/1.0.16/templates/docker-compose.yaml diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/__init__.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/__init__.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/__init__.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/configs.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/configs.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/container.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/container.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/container.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/container.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/depends.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/depends.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/depends.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/deploy.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/deploy.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deploy.py diff --git a/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_mariadb.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/deps.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/deps.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/deps.py +++ b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_postgres.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_redis.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/device.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/device.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/devices.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/devices.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/devices.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/devices.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/dns.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/dns.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/environment.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/environment.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/environment.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/environment.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/error.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/error.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/error.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/formatter.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/formatter.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/formatter.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/functions.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/functions.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/healthcheck.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/healthcheck.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/healthcheck.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/healthcheck.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/labels.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/labels.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/labels.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/notes.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/notes.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/notes.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/portal.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/portal.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/portal.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/portals.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/portals.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/portals.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/ports.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/ports.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/ports.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/render.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/render.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/render.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/resources.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/resources.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/resources.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/restart.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/restart.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/restart.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/storage.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/storage.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/storage.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/sysctls.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/sysctls.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/__init__.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/__init__.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_build_image.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_build_image.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_configs.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_configs.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_container.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_container.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_container.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_container.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_depends.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_depends.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_deps.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_deps.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_deps.py +++ b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_device.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_device.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_device.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_device.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_dns.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_dns.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_environment.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_environment.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_environment.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_environment.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_formatter.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_formatter.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_healthcheck.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_healthcheck.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_healthcheck.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_labels.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_labels.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_notes.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_notes.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_portal.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_portal.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_ports.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_ports.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_render.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_render.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_resources.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_resources.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_restart.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_restart.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/validations.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/validations.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/validations.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/validations.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_mount.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_mount.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_mount_types.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_mount_types.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_sources.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_sources.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_types.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volume_types.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volumes.py b/trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/volumes.py rename to trains/enterprise/asigra-ds-system/1.0.16/templates/library/base_v2_1_0/volumes.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/macros/haproxy_config.macro b/trains/enterprise/asigra-ds-system/1.0.16/templates/macros/haproxy_config.macro similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/macros/haproxy_config.macro rename to trains/enterprise/asigra-ds-system/1.0.16/templates/macros/haproxy_config.macro diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/test_values/basic-values.yaml b/trains/enterprise/asigra-ds-system/1.0.16/templates/test_values/basic-values.yaml similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/test_values/basic-values.yaml rename to trains/enterprise/asigra-ds-system/1.0.16/templates/test_values/basic-values.yaml diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/test_values/cluster-values.yaml b/trains/enterprise/asigra-ds-system/1.0.16/templates/test_values/cluster-values.yaml similarity index 100% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/test_values/cluster-values.yaml rename to trains/enterprise/asigra-ds-system/1.0.16/templates/test_values/cluster-values.yaml diff --git a/trains/enterprise/minio/1.2.0/README.md b/trains/enterprise/minio/1.2.1/README.md similarity index 100% rename from trains/enterprise/minio/1.2.0/README.md rename to trains/enterprise/minio/1.2.1/README.md diff --git a/trains/enterprise/minio/1.2.0/app.yaml b/trains/enterprise/minio/1.2.1/app.yaml similarity index 86% rename from trains/enterprise/minio/1.2.0/app.yaml rename to trains/enterprise/minio/1.2.1/app.yaml index 4f902e948f..87d0f55112 100644 --- a/trains/enterprise/minio/1.2.0/app.yaml +++ b/trains/enterprise/minio/1.2.1/app.yaml @@ -11,8 +11,8 @@ keywords: - minio - cloud - s3 -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -31,4 +31,4 @@ sources: - https://github.com/minio/minio title: MinIO train: enterprise -version: 1.2.0 +version: 1.2.1 diff --git a/trains/enterprise/minio/1.2.0/ix_values.yaml b/trains/enterprise/minio/1.2.1/ix_values.yaml similarity index 100% rename from trains/enterprise/minio/1.2.0/ix_values.yaml rename to trains/enterprise/minio/1.2.1/ix_values.yaml diff --git a/trains/enterprise/minio/1.2.0/migrations/migrate_from_kubernetes b/trains/enterprise/minio/1.2.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migrate_from_kubernetes rename to trains/enterprise/minio/1.2.1/migrations/migrate_from_kubernetes diff --git a/trains/enterprise/minio/1.2.0/migrations/migration_helpers/__init__.py b/trains/enterprise/minio/1.2.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migration_helpers/__init__.py rename to trains/enterprise/minio/1.2.1/migrations/migration_helpers/__init__.py diff --git a/trains/enterprise/minio/1.2.0/migrations/migration_helpers/cpu.py b/trains/enterprise/minio/1.2.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migration_helpers/cpu.py rename to trains/enterprise/minio/1.2.1/migrations/migration_helpers/cpu.py diff --git a/trains/enterprise/minio/1.2.0/migrations/migration_helpers/dns_config.py b/trains/enterprise/minio/1.2.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migration_helpers/dns_config.py rename to trains/enterprise/minio/1.2.1/migrations/migration_helpers/dns_config.py diff --git a/trains/enterprise/minio/1.2.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/enterprise/minio/1.2.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/enterprise/minio/1.2.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/enterprise/minio/1.2.0/migrations/migration_helpers/memory.py b/trains/enterprise/minio/1.2.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migration_helpers/memory.py rename to trains/enterprise/minio/1.2.1/migrations/migration_helpers/memory.py diff --git a/trains/enterprise/minio/1.2.0/migrations/migration_helpers/resources.py b/trains/enterprise/minio/1.2.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migration_helpers/resources.py rename to trains/enterprise/minio/1.2.1/migrations/migration_helpers/resources.py diff --git a/trains/enterprise/minio/1.2.0/migrations/migration_helpers/storage.py b/trains/enterprise/minio/1.2.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/enterprise/minio/1.2.0/migrations/migration_helpers/storage.py rename to trains/enterprise/minio/1.2.1/migrations/migration_helpers/storage.py diff --git a/trains/enterprise/minio/1.2.0/questions.yaml b/trains/enterprise/minio/1.2.1/questions.yaml similarity index 100% rename from trains/enterprise/minio/1.2.0/questions.yaml rename to trains/enterprise/minio/1.2.1/questions.yaml diff --git a/trains/enterprise/minio/1.2.0/templates/docker-compose.yaml b/trains/enterprise/minio/1.2.1/templates/docker-compose.yaml similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/docker-compose.yaml rename to trains/enterprise/minio/1.2.1/templates/docker-compose.yaml diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/__init__.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/__init__.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/configs.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/configs.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/container.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/container.py similarity index 93% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/container.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/container.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/depends.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/depends.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/deploy.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/deploy.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/deps.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/deps.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/deps.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_redis.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/device.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/device.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/device.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/devices.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/devices.py similarity index 93% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/devices.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/devices.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/dns.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/dns.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/environment.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/environment.py similarity index 95% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/environment.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/environment.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/error.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/error.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/error.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/formatter.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/formatter.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/functions.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/functions.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/functions.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/healthcheck.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/healthcheck.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/healthcheck.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/labels.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/labels.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/notes.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/notes.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/portal.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/portal.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/portals.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/portals.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/ports.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/ports.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/render.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/render.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/render.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/resources.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/resources.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/restart.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/restart.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/storage.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/storage.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/storage.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/sysctls.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/sysctls.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_container.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_container.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_deps.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_deps.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_deps.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_device.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_device.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_environment.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_environment.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_environment.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_healthcheck.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/validations.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/validations.py similarity index 94% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/validations.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/validations.py +++ b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_mount.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_sources.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_types.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volume_types.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volumes.py b/trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/volumes.py rename to trains/enterprise/minio/1.2.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/enterprise/minio/1.2.0/templates/test_values/basic-multi-mode-values.yaml b/trains/enterprise/minio/1.2.1/templates/test_values/basic-multi-mode-values.yaml similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/test_values/basic-multi-mode-values.yaml rename to trains/enterprise/minio/1.2.1/templates/test_values/basic-multi-mode-values.yaml diff --git a/trains/enterprise/minio/1.2.0/templates/test_values/basic-values.yaml b/trains/enterprise/minio/1.2.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/test_values/basic-values.yaml rename to trains/enterprise/minio/1.2.1/templates/test_values/basic-values.yaml diff --git a/trains/enterprise/minio/1.2.0/templates/test_values/https-values.yaml b/trains/enterprise/minio/1.2.1/templates/test_values/https-values.yaml similarity index 100% rename from trains/enterprise/minio/1.2.0/templates/test_values/https-values.yaml rename to trains/enterprise/minio/1.2.1/templates/test_values/https-values.yaml diff --git a/trains/enterprise/syncthing/1.1.0/README.md b/trains/enterprise/syncthing/1.1.1/README.md similarity index 100% rename from trains/enterprise/syncthing/1.1.0/README.md rename to trains/enterprise/syncthing/1.1.1/README.md diff --git a/trains/enterprise/syncthing/1.1.0/app.yaml b/trains/enterprise/syncthing/1.1.1/app.yaml similarity index 93% rename from trains/enterprise/syncthing/1.1.0/app.yaml rename to trains/enterprise/syncthing/1.1.1/app.yaml index af06f4c570..e2440f523d 100644 --- a/trains/enterprise/syncthing/1.1.0/app.yaml +++ b/trains/enterprise/syncthing/1.1.1/app.yaml @@ -25,8 +25,8 @@ icon: https://media.sys.truenas.net/apps/syncthing/icons/icon.svg keywords: - sync - file-sharing -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -49,4 +49,4 @@ sources: - https://hub.docker.com/r/syncthing/syncthing title: Syncthing train: enterprise -version: 1.1.0 +version: 1.1.1 diff --git a/trains/enterprise/syncthing/1.1.0/ix_values.yaml b/trains/enterprise/syncthing/1.1.1/ix_values.yaml similarity index 100% rename from trains/enterprise/syncthing/1.1.0/ix_values.yaml rename to trains/enterprise/syncthing/1.1.1/ix_values.yaml diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migrate_from_kubernetes b/trains/enterprise/syncthing/1.1.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migrate_from_kubernetes rename to trains/enterprise/syncthing/1.1.1/migrations/migrate_from_kubernetes diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/__init__.py b/trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/__init__.py rename to trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/__init__.py diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/cpu.py b/trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/cpu.py rename to trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/cpu.py diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/dns_config.py b/trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/dns_config.py rename to trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/dns_config.py diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/memory.py b/trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/memory.py rename to trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/memory.py diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/resources.py b/trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/resources.py rename to trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/resources.py diff --git a/trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/storage.py b/trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/migrations/migration_helpers/storage.py rename to trains/enterprise/syncthing/1.1.1/migrations/migration_helpers/storage.py diff --git a/trains/enterprise/syncthing/1.1.0/questions.yaml b/trains/enterprise/syncthing/1.1.1/questions.yaml similarity index 100% rename from trains/enterprise/syncthing/1.1.0/questions.yaml rename to trains/enterprise/syncthing/1.1.1/questions.yaml diff --git a/trains/enterprise/syncthing/1.1.0/templates/docker-compose.yaml b/trains/enterprise/syncthing/1.1.1/templates/docker-compose.yaml similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/docker-compose.yaml rename to trains/enterprise/syncthing/1.1.1/templates/docker-compose.yaml diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/__init__.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/__init__.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/configs.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/configs.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/container.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/container.py similarity index 93% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/container.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/container.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/depends.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/depends.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/deploy.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/deploy.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/deps.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/deps.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/deps.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/device.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/device.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/devices.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/devices.py similarity index 93% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/devices.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/devices.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/dns.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/dns.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/environment.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/environment.py similarity index 95% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/environment.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/environment.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/error.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/error.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/error.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/formatter.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/formatter.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/functions.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/functions.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/healthcheck.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/healthcheck.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/healthcheck.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/labels.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/labels.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/notes.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/notes.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/portal.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/portal.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/portals.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/portals.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/ports.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/ports.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/render.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/render.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/render.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/resources.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/resources.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/restart.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/restart.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/storage.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/storage.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/sysctls.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/sysctls.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_container.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_container.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_container.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_device.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_device.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_device.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_environment.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_environment.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_functions.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/validations.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/validations.py similarity index 94% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/validations.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/validations.py +++ b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_sources.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_types.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volume_types.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volumes.py b/trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/volumes.py rename to trains/enterprise/syncthing/1.1.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/macros/setup.sh.jinja b/trains/enterprise/syncthing/1.1.1/templates/macros/setup.sh.jinja similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/macros/setup.sh.jinja rename to trains/enterprise/syncthing/1.1.1/templates/macros/setup.sh.jinja diff --git a/trains/enterprise/syncthing/1.1.0/templates/test_values/basic-values.yaml b/trains/enterprise/syncthing/1.1.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/test_values/basic-values.yaml rename to trains/enterprise/syncthing/1.1.1/templates/test_values/basic-values.yaml diff --git a/trains/enterprise/syncthing/1.1.0/templates/test_values/https-values.yaml b/trains/enterprise/syncthing/1.1.1/templates/test_values/https-values.yaml similarity index 100% rename from trains/enterprise/syncthing/1.1.0/templates/test_values/https-values.yaml rename to trains/enterprise/syncthing/1.1.1/templates/test_values/https-values.yaml diff --git a/trains/stable/collabora/1.2.1/README.md b/trains/stable/collabora/1.2.2/README.md similarity index 100% rename from trains/stable/collabora/1.2.1/README.md rename to trains/stable/collabora/1.2.2/README.md diff --git a/trains/stable/collabora/1.2.1/app.yaml b/trains/stable/collabora/1.2.2/app.yaml similarity index 92% rename from trains/stable/collabora/1.2.1/app.yaml rename to trains/stable/collabora/1.2.2/app.yaml index ca5a874281..7d575e686c 100644 --- a/trains/stable/collabora/1.2.1/app.yaml +++ b/trains/stable/collabora/1.2.2/app.yaml @@ -27,8 +27,8 @@ keywords: - office - documents - productivity -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -53,4 +53,4 @@ sources: - https://hub.docker.com/r/collabora/code title: Collabora train: stable -version: 1.2.1 +version: 1.2.2 diff --git a/trains/stable/collabora/1.2.1/ix_values.yaml b/trains/stable/collabora/1.2.2/ix_values.yaml similarity index 100% rename from trains/stable/collabora/1.2.1/ix_values.yaml rename to trains/stable/collabora/1.2.2/ix_values.yaml diff --git a/trains/stable/collabora/1.2.1/migrations/migrate_from_kubernetes b/trains/stable/collabora/1.2.2/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migrate_from_kubernetes rename to trains/stable/collabora/1.2.2/migrations/migrate_from_kubernetes diff --git a/trains/stable/collabora/1.2.1/migrations/migration_helpers/__init__.py b/trains/stable/collabora/1.2.2/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migration_helpers/__init__.py rename to trains/stable/collabora/1.2.2/migrations/migration_helpers/__init__.py diff --git a/trains/stable/collabora/1.2.1/migrations/migration_helpers/cpu.py b/trains/stable/collabora/1.2.2/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migration_helpers/cpu.py rename to trains/stable/collabora/1.2.2/migrations/migration_helpers/cpu.py diff --git a/trains/stable/collabora/1.2.1/migrations/migration_helpers/dns_config.py b/trains/stable/collabora/1.2.2/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migration_helpers/dns_config.py rename to trains/stable/collabora/1.2.2/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/collabora/1.2.1/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/collabora/1.2.2/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/collabora/1.2.2/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/collabora/1.2.1/migrations/migration_helpers/memory.py b/trains/stable/collabora/1.2.2/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migration_helpers/memory.py rename to trains/stable/collabora/1.2.2/migrations/migration_helpers/memory.py diff --git a/trains/stable/collabora/1.2.1/migrations/migration_helpers/resources.py b/trains/stable/collabora/1.2.2/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migration_helpers/resources.py rename to trains/stable/collabora/1.2.2/migrations/migration_helpers/resources.py diff --git a/trains/stable/collabora/1.2.1/migrations/migration_helpers/storage.py b/trains/stable/collabora/1.2.2/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/collabora/1.2.1/migrations/migration_helpers/storage.py rename to trains/stable/collabora/1.2.2/migrations/migration_helpers/storage.py diff --git a/trains/stable/collabora/1.2.1/questions.yaml b/trains/stable/collabora/1.2.2/questions.yaml similarity index 100% rename from trains/stable/collabora/1.2.1/questions.yaml rename to trains/stable/collabora/1.2.2/questions.yaml diff --git a/trains/stable/collabora/1.2.1/templates/docker-compose.yaml b/trains/stable/collabora/1.2.2/templates/docker-compose.yaml similarity index 100% rename from trains/stable/collabora/1.2.1/templates/docker-compose.yaml rename to trains/stable/collabora/1.2.2/templates/docker-compose.yaml diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/__init__.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/__init__.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/configs.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/configs.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/container.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/container.py similarity index 93% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/container.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/container.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/depends.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/depends.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/deploy.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/deploy.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_perms.py similarity index 56% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_perms.py index b3607fa6ab..cdc5a3820a 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_perms.py @@ -1,7 +1,7 @@ -import os import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired +import pathlib +from typing import TYPE_CHECKING + if TYPE_CHECKING: from render import Render @@ -9,44 +9,10 @@ try: from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise except ImportError: from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise class PermsContainer: @@ -76,7 +42,7 @@ def parse_action(self, identifier: str, volume_config: "IxStorage", action_confi gid = action_config.get("gid", None) chmod = action_config.get("chmod", None) recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() is_temporary = False vol_type = volume_config.get("type", "") @@ -284,171 +250,3 @@ def perform_action(action): perform_action(action) print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") """ - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/device.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/device.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/device.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/devices.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/devices.py similarity index 93% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/devices.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/devices.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/dns.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/dns.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/environment.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/environment.py similarity index 95% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/environment.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/environment.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/error.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/error.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/formatter.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/formatter.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/functions.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/functions.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/healthcheck.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/healthcheck.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/healthcheck.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/labels.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/labels.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/notes.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/notes.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/portal.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/portal.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/portals.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/portals.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/ports.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/ports.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/render.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/render.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/resources.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/resources.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/restart.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/restart.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/storage.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/storage.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/sysctls.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/sysctls.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_container.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_container.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_deps.py similarity index 80% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_deps.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_deps.py index f9562ba4f2..a1b7f03a60 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_deps.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_deps.py @@ -29,7 +29,7 @@ def test_add_postgres_missing_config(mock_values): def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -54,7 +54,7 @@ def test_add_postgres(mock_values): ) assert "devices" not in output["services"]["pg_container"] assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" + assert output["services"]["pg_container"]["image"] == "postgres:16" assert output["services"]["pg_container"]["user"] == "999:999" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" @@ -85,7 +85,8 @@ def test_add_postgres(mock_values): "POSTGRES_PORT": "5432", } assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, } assert output["services"]["perms_container"]["restart"] == "on-failure:1" @@ -252,7 +253,7 @@ def test_add_perms_container(mock_values): "test_dataset2": "/mnt/test/2", "test_dataset3": "/mnt/test/3", } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} render = Render(mock_values) @@ -378,3 +379,99 @@ def test_add_perm_action_without_auto_perms_enabled(mock_values): assert "configs" not in output assert "ix-test_perms_container" not in output["services"] assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_device.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_device.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_environment.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_environment.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_functions.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_functions.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_healthcheck.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_healthcheck.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_healthcheck.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_sysctls.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_sysctls.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_volumes.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_volumes.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/validations.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/validations.py similarity index 94% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/validations.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/validations.py +++ b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_types.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volumes.py b/trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/volumes.py rename to trains/stable/collabora/1.2.2/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/collabora/1.2.1/templates/macros/nginx.conf.jinja b/trains/stable/collabora/1.2.2/templates/macros/nginx.conf.jinja similarity index 100% rename from trains/stable/collabora/1.2.1/templates/macros/nginx.conf.jinja rename to trains/stable/collabora/1.2.2/templates/macros/nginx.conf.jinja diff --git a/trains/stable/collabora/1.2.1/templates/test_values/basic-values.yaml b/trains/stable/collabora/1.2.2/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/collabora/1.2.1/templates/test_values/basic-values.yaml rename to trains/stable/collabora/1.2.2/templates/test_values/basic-values.yaml diff --git a/trains/stable/collabora/1.2.1/templates/test_values/https-values.yaml b/trains/stable/collabora/1.2.2/templates/test_values/https-values.yaml similarity index 100% rename from trains/stable/collabora/1.2.1/templates/test_values/https-values.yaml rename to trains/stable/collabora/1.2.2/templates/test_values/https-values.yaml diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/environment.py b/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_device.py b/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_environment.py b/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/diskoverdata/1.4.1/README.md b/trains/stable/diskoverdata/1.4.2/README.md similarity index 100% rename from trains/stable/diskoverdata/1.4.1/README.md rename to trains/stable/diskoverdata/1.4.2/README.md diff --git a/trains/stable/diskoverdata/1.4.1/app.yaml b/trains/stable/diskoverdata/1.4.2/app.yaml similarity index 92% rename from trains/stable/diskoverdata/1.4.1/app.yaml rename to trains/stable/diskoverdata/1.4.2/app.yaml index 6ccc9a553d..cc596c6740 100644 --- a/trains/stable/diskoverdata/1.4.1/app.yaml +++ b/trains/stable/diskoverdata/1.4.2/app.yaml @@ -23,8 +23,8 @@ keywords: - monitoring - management - discovery -lib_version: 2.0.31 -lib_version_hash: e61b4db536830d207e591fea73037ca3f335da01a7e4073bb37392d1ede15873 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -50,4 +50,4 @@ sources: - https://github.com/linuxserver/docker-diskover title: Diskover Data train: stable -version: 1.4.1 +version: 1.4.2 diff --git a/trains/stable/diskoverdata/1.4.1/ix_values.yaml b/trains/stable/diskoverdata/1.4.2/ix_values.yaml similarity index 100% rename from trains/stable/diskoverdata/1.4.1/ix_values.yaml rename to trains/stable/diskoverdata/1.4.2/ix_values.yaml diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migrate_from_kubernetes b/trains/stable/diskoverdata/1.4.2/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migrate_from_kubernetes rename to trains/stable/diskoverdata/1.4.2/migrations/migrate_from_kubernetes diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/__init__.py b/trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/__init__.py rename to trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/__init__.py diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/cpu.py b/trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/cpu.py rename to trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/cpu.py diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/dns_config.py b/trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/dns_config.py rename to trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/memory.py b/trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/memory.py rename to trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/memory.py diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/resources.py b/trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/resources.py rename to trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/resources.py diff --git a/trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/storage.py b/trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/migrations/migration_helpers/storage.py rename to trains/stable/diskoverdata/1.4.2/migrations/migration_helpers/storage.py diff --git a/trains/stable/diskoverdata/1.4.1/questions.yaml b/trains/stable/diskoverdata/1.4.2/questions.yaml similarity index 100% rename from trains/stable/diskoverdata/1.4.1/questions.yaml rename to trains/stable/diskoverdata/1.4.2/questions.yaml diff --git a/trains/stable/diskoverdata/1.4.1/templates/diskover_macros/crontab b/trains/stable/diskoverdata/1.4.2/templates/diskover_macros/crontab similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/diskover_macros/crontab rename to trains/stable/diskoverdata/1.4.2/templates/diskover_macros/crontab diff --git a/trains/stable/diskoverdata/1.4.1/templates/diskover_macros/setup-cron.sh b/trains/stable/diskoverdata/1.4.2/templates/diskover_macros/setup-cron.sh similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/diskover_macros/setup-cron.sh rename to trains/stable/diskoverdata/1.4.2/templates/diskover_macros/setup-cron.sh diff --git a/trains/stable/diskoverdata/1.4.1/templates/docker-compose.yaml b/trains/stable/diskoverdata/1.4.2/templates/docker-compose.yaml similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/docker-compose.yaml rename to trains/stable/diskoverdata/1.4.2/templates/docker-compose.yaml diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/__init__.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/__init__.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/configs.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/configs.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/configs.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/container.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/container.py similarity index 93% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/container.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/container.py index a95e76734c..701f64bfeb 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/container.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/container.py @@ -17,7 +17,7 @@ from .labels import Labels from .ports import Ports from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from .storage import Storage from .sysctls import Sysctls except ImportError: @@ -33,7 +33,7 @@ from labels import Labels from ports import Ports from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise from storage import Storage from sysctls import Sysctls @@ -45,6 +45,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._name: str = name self._image: str = self._resolve_image(image) self._build_image: str = "" + self._pull_policy: str = "" self._user: str = "" self._tty: bool = False self._stdin_open: bool = False @@ -54,6 +55,7 @@ def __init__(self, render_instance: "Render", name: str, image: str): self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly self._cap_add: set[str] = set() self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False self._group_add: set[int | str] = set() self._network_mode: str = "" self._entrypoint: list[str] = [] @@ -130,6 +132,9 @@ def build_image(self, content: list[str | None]): self._build_image = dockerfile self._image = get_image_with_hashed_data(self._image, dockerfile) + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + def set_user(self, user: int, group: int): for i in (user, group): if not isinstance(i, int) or i < 0: @@ -169,6 +174,13 @@ def set_grace_period(self, grace_period: int): raise RenderError(f"Grace period [{grace_period}] cannot be negative") self._grace_period = grace_period + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + def add_caps(self, caps: list[str]): for c in caps: if c in self._cap_add: @@ -230,10 +242,14 @@ def render(self) -> dict[str, Any]: "tty": self._tty, "stdin_open": self._stdin_open, "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), } + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + if self._hostname: result["hostname"] = self._hostname @@ -265,6 +281,12 @@ def render(self) -> dict[str, Any]: if self._shm_size is not None: result["shm_size"] = f"{self._shm_size}M" + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + if self._cap_add: result["cap_add"] = sorted(self._cap_add) diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/depends.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/depends.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/deploy.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/deploy.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/device.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/device.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/devices.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/devices.py similarity index 93% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/devices.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/devices.py index ae22c79d2e..b6139371ee 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/devices.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/devices.py @@ -27,6 +27,8 @@ def _auto_add_devices_from_values(self): if resources.get("gpus", {}).get("use_all_gpus", False): self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): # Host device can be mapped to multiple container devices, diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/dns.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/dns.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/dns.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/environment.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/environment.py similarity index 95% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/environment.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/environment.py index 850a3afd8e..056763ea80 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/environment.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/environment.py @@ -23,10 +23,13 @@ def __init__(self, render_instance: "Render", resources: Resources): # Stores variables that are added by the application developer self._app_dev_variables: dict[str, Any] = {} + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + self._auto_add_variables_from_values() def _auto_add_variables_from_values(self): - self._add_generic_variables() + if not self._skip_generic_variables: + self._add_generic_variables() self._add_nvidia_variables() def _add_generic_variables(self): diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/error.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/error.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/formatter.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/formatter.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/functions.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/functions.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/functions.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/healthcheck.py similarity index 95% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/healthcheck.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/healthcheck.py index 36ae5d90aa..0805329284 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/healthcheck.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/healthcheck.py @@ -22,6 +22,7 @@ def __init__(self, render_instance: "Render"): self._retries: int = 30 self._start_period_sec: int = 10 self._disabled: bool = False + self._use_built_in: bool = False def _get_test(self): if isinstance(self._test, str): @@ -32,6 +33,9 @@ def _get_test(self): def disable(self): self._disabled = True + def use_built_in(self): + self._use_built_in = True + def set_custom_test(self, test: str | list[str]): if self._disabled: raise RenderError("Cannot set custom test when healthcheck is disabled") @@ -53,7 +57,13 @@ def set_retries(self, retries: int): def set_start_period(self, start_period: int): self._start_period_sec = start_period + def has_healthcheck(self): + return not self._use_built_in + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + if self._disabled: return {"disable": True} diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/labels.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/labels.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/notes.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/notes.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/portal.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/portal.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/portals.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/portals.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/ports.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/ports.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/render.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/render.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/resources.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/resources.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/restart.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/restart.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/storage.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/storage.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/sysctls.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/__init__.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/__init__.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_build_image.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_build_image.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_configs.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_configs.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_container.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_container.py similarity index 89% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_container.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_container.py index 61a22a5df2..747ad39357 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_container.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_container.py @@ -50,6 +50,42 @@ def test_non_existing_image(mock_values): render.add_container("test_container", "non_existing_image") +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + def test_tty(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_depends.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_depends.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_device.py similarity index 89% rename from trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_device.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_device.py index 7455c829f6..c44437367d 100644 --- a/trains/stable/collabora/1.2.1/templates/library/base_v2_0_32/tests/test_device.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_device.py @@ -93,6 +93,16 @@ def test_automatically_add_gpu_devices(mock_values): assert output["services"]["test_container"]["group_add"] == [44, 107, 568] +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + def test_remove_gpu_devices(mock_values): mock_values["resources"] = {"gpus": {"use_all_gpus": True}} render = Render(mock_values) diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_dns.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_dns.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_environment.py similarity index 93% rename from trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_environment.py index 209f67551b..d657646582 100644 --- a/trains/enterprise/minio/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_environment.py @@ -47,6 +47,18 @@ def test_auto_add_vars(mock_values): assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + def test_add_from_all_sources(mock_values): mock_values["TZ"] = "Etc/UTC" render = Render(mock_values) diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_formatter.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_formatter.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_healthcheck.py similarity index 95% rename from trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_healthcheck.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_healthcheck.py index fbd488ece4..8fa044290f 100644 --- a/trains/enterprise/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -23,6 +23,14 @@ def test_disable_healthcheck(mock_values): assert output["services"]["test_container"]["healthcheck"] == {"disable": True} +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + def test_set_custom_test(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_labels.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_labels.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_notes.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_notes.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_portal.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_portal.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_ports.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_ports.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_render.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_render.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_resources.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_resources.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_restart.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/tests/test_restart.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/validations.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/validations.py similarity index 94% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/validations.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/validations.py index 13f155dfdb..43dd96b475 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/validations.py +++ b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/validations.py @@ -9,6 +9,13 @@ OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + def valid_sysctl_or_raise(sysctl: str, host_network: bool): if not sysctl: raise RenderError("Sysctl cannot be empty") @@ -139,7 +146,7 @@ def _valid_path_or_raise(path: str): def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] if path in disallowed_devices: raise RenderError(f"Device [{path}] is not allowed to be manually added.") return path diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_mount.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_mount.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_mount_types.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_mount_types.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_sources.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_sources.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_types.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volume_types.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volumes.py b/trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/volumes.py rename to trains/stable/diskoverdata/1.4.2/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/test_values/basic-values.yaml b/trains/stable/diskoverdata/1.4.2/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/diskoverdata/1.4.1/templates/test_values/basic-values.yaml rename to trains/stable/diskoverdata/1.4.2/templates/test_values/basic-values.yaml diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/container.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/deps.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/devices.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/environment.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/validations.py b/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/elastic-search/1.2.0/README.md b/trains/stable/elastic-search/1.2.1/README.md similarity index 100% rename from trains/stable/elastic-search/1.2.0/README.md rename to trains/stable/elastic-search/1.2.1/README.md diff --git a/trains/stable/elastic-search/1.2.0/app.yaml b/trains/stable/elastic-search/1.2.1/app.yaml similarity index 86% rename from trains/stable/elastic-search/1.2.0/app.yaml rename to trains/stable/elastic-search/1.2.1/app.yaml index dda76d26b9..448574c608 100644 --- a/trains/stable/elastic-search/1.2.0/app.yaml +++ b/trains/stable/elastic-search/1.2.1/app.yaml @@ -10,8 +10,8 @@ icon: https://media.sys.truenas.net/apps/elastic-search/icons/icon.svg keywords: - search - elastic -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -29,4 +29,4 @@ sources: - https://www.elastic.co/guide/en/elasticsearch/reference/master/docker.html#docker-configuration-methods title: Elastic Search train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/trains/stable/elastic-search/1.2.0/ix_values.yaml b/trains/stable/elastic-search/1.2.1/ix_values.yaml similarity index 100% rename from trains/stable/elastic-search/1.2.0/ix_values.yaml rename to trains/stable/elastic-search/1.2.1/ix_values.yaml diff --git a/trains/stable/elastic-search/1.2.0/migrations/migrate_from_kubernetes b/trains/stable/elastic-search/1.2.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migrate_from_kubernetes rename to trains/stable/elastic-search/1.2.1/migrations/migrate_from_kubernetes diff --git a/trains/stable/elastic-search/1.2.0/migrations/migration_helpers/__init__.py b/trains/stable/elastic-search/1.2.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migration_helpers/__init__.py rename to trains/stable/elastic-search/1.2.1/migrations/migration_helpers/__init__.py diff --git a/trains/stable/elastic-search/1.2.0/migrations/migration_helpers/cpu.py b/trains/stable/elastic-search/1.2.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migration_helpers/cpu.py rename to trains/stable/elastic-search/1.2.1/migrations/migration_helpers/cpu.py diff --git a/trains/stable/elastic-search/1.2.0/migrations/migration_helpers/dns_config.py b/trains/stable/elastic-search/1.2.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migration_helpers/dns_config.py rename to trains/stable/elastic-search/1.2.1/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/elastic-search/1.2.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/elastic-search/1.2.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/elastic-search/1.2.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/elastic-search/1.2.0/migrations/migration_helpers/memory.py b/trains/stable/elastic-search/1.2.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migration_helpers/memory.py rename to trains/stable/elastic-search/1.2.1/migrations/migration_helpers/memory.py diff --git a/trains/stable/elastic-search/1.2.0/migrations/migration_helpers/resources.py b/trains/stable/elastic-search/1.2.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migration_helpers/resources.py rename to trains/stable/elastic-search/1.2.1/migrations/migration_helpers/resources.py diff --git a/trains/stable/elastic-search/1.2.0/migrations/migration_helpers/storage.py b/trains/stable/elastic-search/1.2.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/migrations/migration_helpers/storage.py rename to trains/stable/elastic-search/1.2.1/migrations/migration_helpers/storage.py diff --git a/trains/stable/elastic-search/1.2.0/questions.yaml b/trains/stable/elastic-search/1.2.1/questions.yaml similarity index 100% rename from trains/stable/elastic-search/1.2.0/questions.yaml rename to trains/stable/elastic-search/1.2.1/questions.yaml diff --git a/trains/stable/elastic-search/1.2.0/templates/docker-compose.yaml b/trains/stable/elastic-search/1.2.1/templates/docker-compose.yaml similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/docker-compose.yaml rename to trains/stable/elastic-search/1.2.1/templates/docker-compose.yaml diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/__init__.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/__init__.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/configs.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/configs.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/container.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/depends.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/depends.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/deploy.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/deploy.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/device.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/device.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/devices.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/dns.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/dns.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/environment.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/error.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/error.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/formatter.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/formatter.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/functions.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/functions.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/labels.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/labels.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/notes.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/notes.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/portal.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/portal.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/portals.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/portals.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/ports.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/ports.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/render.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/render.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/resources.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/resources.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/restart.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/restart.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/storage.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/storage.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/sysctls.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/sysctls.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_functions.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_functions.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_sysctls.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_sysctls.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_volumes.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_volumes.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/validations.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_types.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volumes.py b/trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/library/base_v2_0_32/volumes.py rename to trains/stable/elastic-search/1.2.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/elastic-search/1.2.0/templates/test_values/basic-values.yaml b/trains/stable/elastic-search/1.2.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/test_values/basic-values.yaml rename to trains/stable/elastic-search/1.2.1/templates/test_values/basic-values.yaml diff --git a/trains/stable/elastic-search/1.2.0/templates/test_values/https-values.yaml b/trains/stable/elastic-search/1.2.1/templates/test_values/https-values.yaml similarity index 100% rename from trains/stable/elastic-search/1.2.0/templates/test_values/https-values.yaml rename to trains/stable/elastic-search/1.2.1/templates/test_values/https-values.yaml diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/container.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/deps.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/devices.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/environment.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/healthcheck.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_container.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_deps.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_device.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_environment.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_healthcheck.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/validations.py b/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/emby/1.2.3/README.md b/trains/stable/emby/1.2.4/README.md similarity index 100% rename from trains/stable/emby/1.2.3/README.md rename to trains/stable/emby/1.2.4/README.md diff --git a/trains/stable/emby/1.2.3/app.yaml b/trains/stable/emby/1.2.4/app.yaml similarity index 91% rename from trains/stable/emby/1.2.3/app.yaml rename to trains/stable/emby/1.2.4/app.yaml index 413479181c..e6ac2c0569 100644 --- a/trains/stable/emby/1.2.3/app.yaml +++ b/trains/stable/emby/1.2.4/app.yaml @@ -27,8 +27,8 @@ keywords: - series - tv - streaming -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -49,4 +49,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/emby title: Emby Server train: stable -version: 1.2.3 +version: 1.2.4 diff --git a/trains/stable/emby/1.2.3/ix_values.yaml b/trains/stable/emby/1.2.4/ix_values.yaml similarity index 100% rename from trains/stable/emby/1.2.3/ix_values.yaml rename to trains/stable/emby/1.2.4/ix_values.yaml diff --git a/trains/stable/emby/1.2.3/migrations/migrate_from_kubernetes b/trains/stable/emby/1.2.4/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migrate_from_kubernetes rename to trains/stable/emby/1.2.4/migrations/migrate_from_kubernetes diff --git a/trains/stable/emby/1.2.3/migrations/migration_helpers/__init__.py b/trains/stable/emby/1.2.4/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migration_helpers/__init__.py rename to trains/stable/emby/1.2.4/migrations/migration_helpers/__init__.py diff --git a/trains/stable/emby/1.2.3/migrations/migration_helpers/cpu.py b/trains/stable/emby/1.2.4/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migration_helpers/cpu.py rename to trains/stable/emby/1.2.4/migrations/migration_helpers/cpu.py diff --git a/trains/stable/emby/1.2.3/migrations/migration_helpers/dns_config.py b/trains/stable/emby/1.2.4/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migration_helpers/dns_config.py rename to trains/stable/emby/1.2.4/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/emby/1.2.3/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/emby/1.2.4/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/emby/1.2.4/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/emby/1.2.3/migrations/migration_helpers/memory.py b/trains/stable/emby/1.2.4/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migration_helpers/memory.py rename to trains/stable/emby/1.2.4/migrations/migration_helpers/memory.py diff --git a/trains/stable/emby/1.2.3/migrations/migration_helpers/resources.py b/trains/stable/emby/1.2.4/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migration_helpers/resources.py rename to trains/stable/emby/1.2.4/migrations/migration_helpers/resources.py diff --git a/trains/stable/emby/1.2.3/migrations/migration_helpers/storage.py b/trains/stable/emby/1.2.4/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/emby/1.2.3/migrations/migration_helpers/storage.py rename to trains/stable/emby/1.2.4/migrations/migration_helpers/storage.py diff --git a/trains/stable/emby/1.2.3/questions.yaml b/trains/stable/emby/1.2.4/questions.yaml similarity index 100% rename from trains/stable/emby/1.2.3/questions.yaml rename to trains/stable/emby/1.2.4/questions.yaml diff --git a/trains/stable/emby/1.2.3/templates/docker-compose.yaml b/trains/stable/emby/1.2.4/templates/docker-compose.yaml similarity index 100% rename from trains/stable/emby/1.2.3/templates/docker-compose.yaml rename to trains/stable/emby/1.2.4/templates/docker-compose.yaml diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/__init__.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/__init__.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/configs.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/configs.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/container.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/depends.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/depends.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/deploy.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/deploy.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/device.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/device.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/devices.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/dns.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/dns.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/environment.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/error.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/error.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/formatter.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/formatter.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/functions.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/functions.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/labels.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/labels.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/notes.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/notes.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/portal.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/portal.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/portals.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/portals.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/ports.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/ports.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/render.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/render.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/resources.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/resources.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/restart.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/restart.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/storage.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/storage.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/sysctls.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/__init__.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/__init__.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_build_image.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_build_image.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_configs.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_configs.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_depends.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_depends.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_dns.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_dns.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_formatter.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_formatter.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_labels.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_labels.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_notes.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_notes.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_portal.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_portal.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_ports.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_ports.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_render.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_render.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_resources.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_resources.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_restart.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_restart.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/validations.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_mount.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_mount.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_mount_types.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_mount_types.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_sources.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_sources.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_types.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volume_types.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volumes.py b/trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/volumes.py rename to trains/stable/emby/1.2.4/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/emby/1.2.3/templates/test_values/basic-values.yaml b/trains/stable/emby/1.2.4/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/emby/1.2.3/templates/test_values/basic-values.yaml rename to trains/stable/emby/1.2.4/templates/test_values/basic-values.yaml diff --git a/trains/stable/emby/1.2.3/templates/test_values/hostnet-values.yaml b/trains/stable/emby/1.2.4/templates/test_values/hostnet-values.yaml similarity index 100% rename from trains/stable/emby/1.2.3/templates/test_values/hostnet-values.yaml rename to trains/stable/emby/1.2.4/templates/test_values/hostnet-values.yaml diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/container.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/deps.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/devices.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/environment.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/healthcheck.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_container.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_deps.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_device.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_environment.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_healthcheck.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/validations.py b/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/home-assistant/1.3.4/README.md b/trains/stable/home-assistant/1.3.5/README.md similarity index 100% rename from trains/stable/home-assistant/1.3.4/README.md rename to trains/stable/home-assistant/1.3.5/README.md diff --git a/trains/stable/home-assistant/1.3.4/app.yaml b/trains/stable/home-assistant/1.3.5/app.yaml similarity index 91% rename from trains/stable/home-assistant/1.3.4/app.yaml rename to trains/stable/home-assistant/1.3.5/app.yaml index 3d6c12f248..1c470d7249 100644 --- a/trains/stable/home-assistant/1.3.4/app.yaml +++ b/trains/stable/home-assistant/1.3.5/app.yaml @@ -20,8 +20,8 @@ icon: https://media.sys.truenas.net/apps/home-assistant/icons/icon.png keywords: - home-automation - assistant -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -45,4 +45,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/home-assistant title: Home Assistant train: stable -version: 1.3.4 +version: 1.3.5 diff --git a/trains/stable/home-assistant/1.3.4/ix_values.yaml b/trains/stable/home-assistant/1.3.5/ix_values.yaml similarity index 100% rename from trains/stable/home-assistant/1.3.4/ix_values.yaml rename to trains/stable/home-assistant/1.3.5/ix_values.yaml diff --git a/trains/stable/home-assistant/1.3.4/migrations/migrate_from_kubernetes b/trains/stable/home-assistant/1.3.5/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migrate_from_kubernetes rename to trains/stable/home-assistant/1.3.5/migrations/migrate_from_kubernetes diff --git a/trains/stable/home-assistant/1.3.4/migrations/migration_helpers/__init__.py b/trains/stable/home-assistant/1.3.5/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migration_helpers/__init__.py rename to trains/stable/home-assistant/1.3.5/migrations/migration_helpers/__init__.py diff --git a/trains/stable/home-assistant/1.3.4/migrations/migration_helpers/cpu.py b/trains/stable/home-assistant/1.3.5/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migration_helpers/cpu.py rename to trains/stable/home-assistant/1.3.5/migrations/migration_helpers/cpu.py diff --git a/trains/stable/home-assistant/1.3.4/migrations/migration_helpers/dns_config.py b/trains/stable/home-assistant/1.3.5/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migration_helpers/dns_config.py rename to trains/stable/home-assistant/1.3.5/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/home-assistant/1.3.4/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/home-assistant/1.3.5/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/home-assistant/1.3.5/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/home-assistant/1.3.4/migrations/migration_helpers/memory.py b/trains/stable/home-assistant/1.3.5/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migration_helpers/memory.py rename to trains/stable/home-assistant/1.3.5/migrations/migration_helpers/memory.py diff --git a/trains/stable/home-assistant/1.3.4/migrations/migration_helpers/resources.py b/trains/stable/home-assistant/1.3.5/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migration_helpers/resources.py rename to trains/stable/home-assistant/1.3.5/migrations/migration_helpers/resources.py diff --git a/trains/stable/home-assistant/1.3.4/migrations/migration_helpers/storage.py b/trains/stable/home-assistant/1.3.5/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/migrations/migration_helpers/storage.py rename to trains/stable/home-assistant/1.3.5/migrations/migration_helpers/storage.py diff --git a/trains/stable/home-assistant/1.3.4/questions.yaml b/trains/stable/home-assistant/1.3.5/questions.yaml similarity index 100% rename from trains/stable/home-assistant/1.3.4/questions.yaml rename to trains/stable/home-assistant/1.3.5/questions.yaml diff --git a/trains/stable/home-assistant/1.3.4/templates/docker-compose.yaml b/trains/stable/home-assistant/1.3.5/templates/docker-compose.yaml similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/docker-compose.yaml rename to trains/stable/home-assistant/1.3.5/templates/docker-compose.yaml diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/__init__.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/__init__.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/configs.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/configs.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/container.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/depends.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/depends.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/deploy.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/deploy.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/device.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/device.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/devices.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/dns.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/dns.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/environment.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/error.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/error.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/formatter.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/formatter.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/functions.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/functions.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/labels.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/labels.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/notes.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/notes.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/portal.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/portal.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/portals.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/portals.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/ports.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/ports.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/render.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/render.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/resources.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/resources.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/restart.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/restart.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/storage.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/storage.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/sysctls.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/__init__.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/__init__.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_build_image.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_build_image.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_configs.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_configs.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_depends.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_depends.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_dns.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_dns.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_formatter.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_formatter.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_labels.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_labels.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_notes.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_notes.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_portal.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_portal.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_ports.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_ports.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_render.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_render.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_resources.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_resources.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_restart.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_restart.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/validations.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_mount.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_mount.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_mount_types.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_mount_types.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_sources.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_sources.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_types.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volume_types.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volumes.py b/trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/volumes.py rename to trains/stable/home-assistant/1.3.5/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/home-assistant/1.3.4/templates/macros/config.sh.jinja b/trains/stable/home-assistant/1.3.5/templates/macros/config.sh.jinja similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/macros/config.sh.jinja rename to trains/stable/home-assistant/1.3.5/templates/macros/config.sh.jinja diff --git a/trains/stable/home-assistant/1.3.4/templates/macros/config.yaml.jinja b/trains/stable/home-assistant/1.3.5/templates/macros/config.yaml.jinja similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/macros/config.yaml.jinja rename to trains/stable/home-assistant/1.3.5/templates/macros/config.yaml.jinja diff --git a/trains/stable/home-assistant/1.3.4/templates/test_values/basic-values.yaml b/trains/stable/home-assistant/1.3.5/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/home-assistant/1.3.4/templates/test_values/basic-values.yaml rename to trains/stable/home-assistant/1.3.5/templates/test_values/basic-values.yaml diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/deps.py b/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_deps.py b/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/ix-app/1.1.1/README.md b/trains/stable/ix-app/1.1.2/README.md similarity index 100% rename from trains/stable/ix-app/1.1.1/README.md rename to trains/stable/ix-app/1.1.2/README.md diff --git a/trains/stable/ix-app/1.1.1/app.yaml b/trains/stable/ix-app/1.1.2/app.yaml similarity index 78% rename from trains/stable/ix-app/1.1.1/app.yaml rename to trains/stable/ix-app/1.1.2/app.yaml index e6ba36c186..800aa762a2 100644 --- a/trains/stable/ix-app/1.1.1/app.yaml +++ b/trains/stable/ix-app/1.1.2/app.yaml @@ -7,8 +7,8 @@ home: https://www.truenas.com/ host_mounts: [] icon: https://media.sys.truenas.net/apps/ix-chart/icons/icon.webp keywords: [] -lib_version: 2.0.34 -lib_version_hash: 54c507c0a47e2a10aee421ec5a67c04f73692bd865d4d5057f57711e322a7951 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -19,4 +19,4 @@ screenshots: [] sources: [] title: iX App train: stable -version: 1.1.1 +version: 1.1.2 diff --git a/trains/stable/ix-app/1.1.1/ix_values.yaml b/trains/stable/ix-app/1.1.2/ix_values.yaml similarity index 100% rename from trains/stable/ix-app/1.1.1/ix_values.yaml rename to trains/stable/ix-app/1.1.2/ix_values.yaml diff --git a/trains/stable/ix-app/1.1.1/migrations/migrate_from_kubernetes b/trains/stable/ix-app/1.1.2/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migrate_from_kubernetes rename to trains/stable/ix-app/1.1.2/migrations/migrate_from_kubernetes diff --git a/trains/stable/ix-app/1.1.1/migrations/migration_helpers/__init__.py b/trains/stable/ix-app/1.1.2/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migration_helpers/__init__.py rename to trains/stable/ix-app/1.1.2/migrations/migration_helpers/__init__.py diff --git a/trains/stable/ix-app/1.1.1/migrations/migration_helpers/cpu.py b/trains/stable/ix-app/1.1.2/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migration_helpers/cpu.py rename to trains/stable/ix-app/1.1.2/migrations/migration_helpers/cpu.py diff --git a/trains/stable/ix-app/1.1.1/migrations/migration_helpers/dns_config.py b/trains/stable/ix-app/1.1.2/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migration_helpers/dns_config.py rename to trains/stable/ix-app/1.1.2/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/ix-app/1.1.1/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/ix-app/1.1.2/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/ix-app/1.1.2/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/ix-app/1.1.1/migrations/migration_helpers/memory.py b/trains/stable/ix-app/1.1.2/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migration_helpers/memory.py rename to trains/stable/ix-app/1.1.2/migrations/migration_helpers/memory.py diff --git a/trains/stable/ix-app/1.1.1/migrations/migration_helpers/resources.py b/trains/stable/ix-app/1.1.2/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migration_helpers/resources.py rename to trains/stable/ix-app/1.1.2/migrations/migration_helpers/resources.py diff --git a/trains/stable/ix-app/1.1.1/migrations/migration_helpers/storage.py b/trains/stable/ix-app/1.1.2/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/ix-app/1.1.1/migrations/migration_helpers/storage.py rename to trains/stable/ix-app/1.1.2/migrations/migration_helpers/storage.py diff --git a/trains/stable/ix-app/1.1.1/questions.yaml b/trains/stable/ix-app/1.1.2/questions.yaml similarity index 100% rename from trains/stable/ix-app/1.1.1/questions.yaml rename to trains/stable/ix-app/1.1.2/questions.yaml diff --git a/trains/stable/ix-app/1.1.1/templates/docker-compose.yaml b/trains/stable/ix-app/1.1.2/templates/docker-compose.yaml similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/docker-compose.yaml rename to trains/stable/ix-app/1.1.2/templates/docker-compose.yaml diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/__init__.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/__init__.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/configs.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/configs.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/container.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/depends.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/depends.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/deploy.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/deploy.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/device.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/device.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/devices.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/dns.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/dns.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/environment.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/error.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/error.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/formatter.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/formatter.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/functions.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/functions.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/labels.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/labels.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/notes.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/notes.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/portal.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/portal.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/portals.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/portals.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/ports.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/ports.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/render.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/render.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/resources.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/resources.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/restart.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/restart.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/storage.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/storage.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/sysctls.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/__init__.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/__init__.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_build_image.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_build_image.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_configs.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_configs.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_depends.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_depends.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_dns.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_dns.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_formatter.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_formatter.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_labels.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_labels.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_notes.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_notes.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_portal.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_portal.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_ports.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_ports.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_render.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_render.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_resources.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_resources.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_restart.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/tests/test_restart.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/validations.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_mount.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_mount.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_mount_types.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_mount_types.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_sources.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_sources.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_types.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volume_types.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volumes.py b/trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/library/base_v2_0_34/volumes.py rename to trains/stable/ix-app/1.1.2/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/ix-app/1.1.1/templates/test_values/basic-values.yaml b/trains/stable/ix-app/1.1.2/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/ix-app/1.1.1/templates/test_values/basic-values.yaml rename to trains/stable/ix-app/1.1.2/templates/test_values/basic-values.yaml diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/container.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/deps.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/devices.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/environment.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/functions.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/functions.py deleted file mode 100644 index a8799c3963..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/functions.py +++ /dev/null @@ -1,111 +0,0 @@ -import re -import bcrypt -import secrets -from base64 import b64encode -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError -except ImportError: - from error import RenderError - - -class Functions: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def _bcrypt_hash(self, password): - hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") - return hashed - - def _htpasswd(self, username, password): - hashed = self._bcrypt_hash(password) - return username + ":" + hashed - - def _secure_string(self, length): - return secrets.token_urlsafe(length) - - def _basic_auth(self, username, password): - return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") - - def _basic_auth_header(self, username, password): - return f"Basic {self._basic_auth(username, password)}" - - def _fail(self, message): - raise RenderError(message) - - def _camel_case(self, string): - return string.title() - - def _auto_cast(self, value): - try: - return int(value) - except ValueError: - pass - - try: - return float(value) - except ValueError: - pass - - if value.lower() in ["true", "false"]: - return value.lower() == "true" - - return value - - def _match_regex(self, value, regex): - if not re.match(regex, value): - return False - return True - - def _must_match_regex(self, value, regex): - if not self._match_regex(value, regex): - raise RenderError(f"Expected [{value}] to match [{regex}]") - return value - - def _is_boolean(self, string): - return string.lower() in ["true", "false"] - - def _is_number(self, string): - try: - float(string) - return True - except ValueError: - return False - - def _copy_dict(self, dict): - return dict.copy() - - def _merge_dicts(self, *dicts): - merged_dict = {} - for dictionary in dicts: - merged_dict.update(dictionary) - return merged_dict - - def _disallow_chars(self, string, chars, key): - for char in chars: - if char in string: - raise RenderError(f"Disallowed character [{char}] in [{key}]") - - def func_map(self): - # TODO: Check what is no longer used and remove - return { - "auto_cast": self._auto_cast, - "basic_auth_header": self._basic_auth_header, - "basic_auth": self._basic_auth, - "bcrypt_hash": self._bcrypt_hash, - "camel_case": self._camel_case, - "copy_dict": self._copy_dict, - "fail": self._fail, - "htpasswd": self._htpasswd, - "is_boolean": self._is_boolean, - "is_number": self._is_number, - "match_regex": self._match_regex, - "merge_dicts": self._merge_dicts, - "must_match_regex": self._must_match_regex, - "secure_string": self._secure_string, - "disallow_chars": self._disallow_chars, - } diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/healthcheck.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_container.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_deps.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_device.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_environment.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_healthcheck.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/validations.py b/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/minio/1.2.1/README.md b/trains/stable/minio/1.2.2/README.md similarity index 100% rename from trains/stable/minio/1.2.1/README.md rename to trains/stable/minio/1.2.2/README.md diff --git a/trains/stable/minio/1.2.1/app.yaml b/trains/stable/minio/1.2.2/app.yaml similarity index 87% rename from trains/stable/minio/1.2.1/app.yaml rename to trains/stable/minio/1.2.2/app.yaml index 80c2aa187c..f8b459a008 100644 --- a/trains/stable/minio/1.2.1/app.yaml +++ b/trains/stable/minio/1.2.2/app.yaml @@ -10,8 +10,8 @@ keywords: - storage - object-storage - S3 -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -31,4 +31,4 @@ sources: - https://github.com/minio/minio title: MinIO train: stable -version: 1.2.1 +version: 1.2.2 diff --git a/trains/stable/minio/1.2.1/ix_values.yaml b/trains/stable/minio/1.2.2/ix_values.yaml similarity index 100% rename from trains/stable/minio/1.2.1/ix_values.yaml rename to trains/stable/minio/1.2.2/ix_values.yaml diff --git a/trains/stable/minio/1.2.1/migrations/migrate_from_kubernetes b/trains/stable/minio/1.2.2/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migrate_from_kubernetes rename to trains/stable/minio/1.2.2/migrations/migrate_from_kubernetes diff --git a/trains/stable/minio/1.2.1/migrations/migration_helpers/__init__.py b/trains/stable/minio/1.2.2/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migration_helpers/__init__.py rename to trains/stable/minio/1.2.2/migrations/migration_helpers/__init__.py diff --git a/trains/stable/minio/1.2.1/migrations/migration_helpers/cpu.py b/trains/stable/minio/1.2.2/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migration_helpers/cpu.py rename to trains/stable/minio/1.2.2/migrations/migration_helpers/cpu.py diff --git a/trains/stable/minio/1.2.1/migrations/migration_helpers/dns_config.py b/trains/stable/minio/1.2.2/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migration_helpers/dns_config.py rename to trains/stable/minio/1.2.2/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/minio/1.2.1/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/minio/1.2.2/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/minio/1.2.2/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/minio/1.2.1/migrations/migration_helpers/memory.py b/trains/stable/minio/1.2.2/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migration_helpers/memory.py rename to trains/stable/minio/1.2.2/migrations/migration_helpers/memory.py diff --git a/trains/stable/minio/1.2.1/migrations/migration_helpers/resources.py b/trains/stable/minio/1.2.2/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migration_helpers/resources.py rename to trains/stable/minio/1.2.2/migrations/migration_helpers/resources.py diff --git a/trains/stable/minio/1.2.1/migrations/migration_helpers/storage.py b/trains/stable/minio/1.2.2/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/minio/1.2.1/migrations/migration_helpers/storage.py rename to trains/stable/minio/1.2.2/migrations/migration_helpers/storage.py diff --git a/trains/stable/minio/1.2.1/questions.yaml b/trains/stable/minio/1.2.2/questions.yaml similarity index 100% rename from trains/stable/minio/1.2.1/questions.yaml rename to trains/stable/minio/1.2.2/questions.yaml diff --git a/trains/stable/minio/1.2.1/templates/docker-compose.yaml b/trains/stable/minio/1.2.2/templates/docker-compose.yaml similarity index 100% rename from trains/stable/minio/1.2.1/templates/docker-compose.yaml rename to trains/stable/minio/1.2.2/templates/docker-compose.yaml diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/__init__.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/__init__.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/configs.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/configs.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/container.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/depends.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/depends.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/deploy.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/deploy.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/device.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/device.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/devices.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/dns.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/dns.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/environment.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/error.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/error.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/formatter.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/formatter.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/functions.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/functions.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/labels.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/labels.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/notes.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/notes.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/portal.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/portal.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/portals.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/portals.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/ports.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/ports.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/render.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/render.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/resources.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/resources.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/restart.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/restart.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/storage.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/storage.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/sysctls.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/__init__.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/__init__.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_build_image.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_build_image.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_configs.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_configs.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_depends.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_depends.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_dns.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_dns.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_formatter.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_formatter.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_labels.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_labels.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_notes.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_notes.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_portal.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_portal.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_ports.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_ports.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_render.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_render.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_resources.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_resources.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_restart.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_restart.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/validations.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_mount.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_mount.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_mount_types.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_mount_types.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_sources.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_sources.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_types.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volume_types.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volumes.py b/trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/volumes.py rename to trains/stable/minio/1.2.2/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/minio/1.2.1/templates/test_values/basic-values.yaml b/trains/stable/minio/1.2.2/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/minio/1.2.1/templates/test_values/basic-values.yaml rename to trains/stable/minio/1.2.2/templates/test_values/basic-values.yaml diff --git a/trains/stable/minio/1.2.1/templates/test_values/https-values.yaml b/trains/stable/minio/1.2.2/templates/test_values/https-values.yaml similarity index 100% rename from trains/stable/minio/1.2.1/templates/test_values/https-values.yaml rename to trains/stable/minio/1.2.2/templates/test_values/https-values.yaml diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/container.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/deps.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/devices.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/environment.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/validations.py b/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/netdata/1.2.0/README.md b/trains/stable/netdata/1.2.1/README.md similarity index 100% rename from trains/stable/netdata/1.2.0/README.md rename to trains/stable/netdata/1.2.1/README.md diff --git a/trains/stable/netdata/1.2.0/app.yaml b/trains/stable/netdata/1.2.1/app.yaml similarity index 94% rename from trains/stable/netdata/1.2.0/app.yaml rename to trains/stable/netdata/1.2.1/app.yaml index dc6965043e..2d41527b91 100644 --- a/trains/stable/netdata/1.2.0/app.yaml +++ b/trains/stable/netdata/1.2.1/app.yaml @@ -34,8 +34,8 @@ keywords: - alerting - metric - monitoring -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -58,4 +58,4 @@ sources: - https://github.com/netdata/netdata title: Netdata train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/trains/stable/netdata/1.2.0/ix_values.yaml b/trains/stable/netdata/1.2.1/ix_values.yaml similarity index 100% rename from trains/stable/netdata/1.2.0/ix_values.yaml rename to trains/stable/netdata/1.2.1/ix_values.yaml diff --git a/trains/stable/netdata/1.2.0/migrations/migrate_from_kubernetes b/trains/stable/netdata/1.2.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migrate_from_kubernetes rename to trains/stable/netdata/1.2.1/migrations/migrate_from_kubernetes diff --git a/trains/stable/netdata/1.2.0/migrations/migration_helpers/__init__.py b/trains/stable/netdata/1.2.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migration_helpers/__init__.py rename to trains/stable/netdata/1.2.1/migrations/migration_helpers/__init__.py diff --git a/trains/stable/netdata/1.2.0/migrations/migration_helpers/cpu.py b/trains/stable/netdata/1.2.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migration_helpers/cpu.py rename to trains/stable/netdata/1.2.1/migrations/migration_helpers/cpu.py diff --git a/trains/stable/netdata/1.2.0/migrations/migration_helpers/dns_config.py b/trains/stable/netdata/1.2.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migration_helpers/dns_config.py rename to trains/stable/netdata/1.2.1/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/netdata/1.2.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/netdata/1.2.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/netdata/1.2.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/netdata/1.2.0/migrations/migration_helpers/memory.py b/trains/stable/netdata/1.2.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migration_helpers/memory.py rename to trains/stable/netdata/1.2.1/migrations/migration_helpers/memory.py diff --git a/trains/stable/netdata/1.2.0/migrations/migration_helpers/resources.py b/trains/stable/netdata/1.2.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migration_helpers/resources.py rename to trains/stable/netdata/1.2.1/migrations/migration_helpers/resources.py diff --git a/trains/stable/netdata/1.2.0/migrations/migration_helpers/storage.py b/trains/stable/netdata/1.2.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/netdata/1.2.0/migrations/migration_helpers/storage.py rename to trains/stable/netdata/1.2.1/migrations/migration_helpers/storage.py diff --git a/trains/stable/netdata/1.2.0/questions.yaml b/trains/stable/netdata/1.2.1/questions.yaml similarity index 100% rename from trains/stable/netdata/1.2.0/questions.yaml rename to trains/stable/netdata/1.2.1/questions.yaml diff --git a/trains/stable/netdata/1.2.0/templates/docker-compose.yaml b/trains/stable/netdata/1.2.1/templates/docker-compose.yaml similarity index 100% rename from trains/stable/netdata/1.2.0/templates/docker-compose.yaml rename to trains/stable/netdata/1.2.1/templates/docker-compose.yaml diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/__init__.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/__init__.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/configs.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/configs.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/container.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/depends.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/depends.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/deploy.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/deploy.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/device.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/device.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/devices.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/dns.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/dns.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/environment.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/error.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/error.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/formatter.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/formatter.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/functions.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/functions.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/labels.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/labels.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/notes.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/notes.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/portal.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/portal.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/portals.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/portals.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/ports.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/ports.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/render.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/render.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/resources.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/resources.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/restart.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/restart.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/storage.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/storage.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/sysctls.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/validations.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_types.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volumes.py b/trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/netdata/1.2.0/templates/library/base_v2_0_32/volumes.py rename to trains/stable/netdata/1.2.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/netdata/1.2.0/templates/test_values/basic-values.yaml b/trains/stable/netdata/1.2.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/netdata/1.2.0/templates/test_values/basic-values.yaml rename to trains/stable/netdata/1.2.1/templates/test_values/basic-values.yaml diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/container.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/deps.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/devices.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/environment.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/functions.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/functions.py deleted file mode 100644 index a8799c3963..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/functions.py +++ /dev/null @@ -1,111 +0,0 @@ -import re -import bcrypt -import secrets -from base64 import b64encode -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError -except ImportError: - from error import RenderError - - -class Functions: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def _bcrypt_hash(self, password): - hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") - return hashed - - def _htpasswd(self, username, password): - hashed = self._bcrypt_hash(password) - return username + ":" + hashed - - def _secure_string(self, length): - return secrets.token_urlsafe(length) - - def _basic_auth(self, username, password): - return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") - - def _basic_auth_header(self, username, password): - return f"Basic {self._basic_auth(username, password)}" - - def _fail(self, message): - raise RenderError(message) - - def _camel_case(self, string): - return string.title() - - def _auto_cast(self, value): - try: - return int(value) - except ValueError: - pass - - try: - return float(value) - except ValueError: - pass - - if value.lower() in ["true", "false"]: - return value.lower() == "true" - - return value - - def _match_regex(self, value, regex): - if not re.match(regex, value): - return False - return True - - def _must_match_regex(self, value, regex): - if not self._match_regex(value, regex): - raise RenderError(f"Expected [{value}] to match [{regex}]") - return value - - def _is_boolean(self, string): - return string.lower() in ["true", "false"] - - def _is_number(self, string): - try: - float(string) - return True - except ValueError: - return False - - def _copy_dict(self, dict): - return dict.copy() - - def _merge_dicts(self, *dicts): - merged_dict = {} - for dictionary in dicts: - merged_dict.update(dictionary) - return merged_dict - - def _disallow_chars(self, string, chars, key): - for char in chars: - if char in string: - raise RenderError(f"Disallowed character [{char}] in [{key}]") - - def func_map(self): - # TODO: Check what is no longer used and remove - return { - "auto_cast": self._auto_cast, - "basic_auth_header": self._basic_auth_header, - "basic_auth": self._basic_auth, - "bcrypt_hash": self._bcrypt_hash, - "camel_case": self._camel_case, - "copy_dict": self._copy_dict, - "fail": self._fail, - "htpasswd": self._htpasswd, - "is_boolean": self._is_boolean, - "is_number": self._is_number, - "match_regex": self._match_regex, - "merge_dicts": self._merge_dicts, - "must_match_regex": self._must_match_regex, - "secure_string": self._secure_string, - "disallow_chars": self._disallow_chars, - } diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/healthcheck.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/storage.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/storage.py deleted file mode 100644 index 3e5b629790..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/storage.py +++ /dev/null @@ -1,106 +0,0 @@ -from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .validations import valid_fs_path_or_raise - from .volume_mount import VolumeMount -except ImportError: - from error import RenderError - from validations import valid_fs_path_or_raise - from volume_mount import VolumeMount - - -class IxStorageTmpfsConfig(TypedDict): - size: NotRequired[int] - mode: NotRequired[str] - - -class AclConfig(TypedDict, total=False): - path: str - - -class IxStorageHostPathConfig(TypedDict): - path: NotRequired[str] # Either this or acl.path must be set - acl_enable: NotRequired[bool] - acl: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageIxVolumeConfig(TypedDict): - dataset_name: str - acl_enable: NotRequired[bool] - acl_entries: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageVolumeConfig(TypedDict): - volume_name: NotRequired[str] - nocopy: NotRequired[bool] - auto_permissions: NotRequired[bool] - - -class IxStorageNfsConfig(TypedDict): - server: str - path: str - options: NotRequired[list[str]] - - -class IxStorageCifsConfig(TypedDict): - server: str - path: str - username: str - password: str - domain: NotRequired[str] - options: NotRequired[list[str]] - - -IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] -IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] -IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] - - -class IxStorage(TypedDict): - type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] - read_only: NotRequired[bool] - - ix_volume_config: NotRequired[IxStorageIxVolumeConfig] - host_path_config: NotRequired[IxStorageHostPathConfig] - tmpfs_config: NotRequired[IxStorageTmpfsConfig] - volume_config: NotRequired[IxStorageVolumeConfig] - nfs_config: NotRequired[IxStorageNfsConfig] - cifs_config: NotRequired[IxStorageCifsConfig] - - -class Storage: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._volume_mounts: set[VolumeMount] = set() - - def add(self, mount_path: str, config: "IxStorage"): - mount_path = valid_fs_path_or_raise(mount_path) - if mount_path in [m.mount_path for m in self._volume_mounts]: - raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") - - volume_mount = VolumeMount(self._render_instance, mount_path, config) - self._volume_mounts.add(volume_mount) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - cfg: "IxStorage" = { - "type": "host_path", - "read_only": read_only, - "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, - } - self.add(mount_path, cfg) - - def has_mounts(self) -> bool: - return bool(self._volume_mounts) - - def render(self): - return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_container.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_deps.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_device.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_environment.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_functions.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_functions.py deleted file mode 100644 index a75e7c4084..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_functions.py +++ /dev/null @@ -1,65 +0,0 @@ -import re -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_funcs(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - tests = [ - {"func": "auto_cast", "values": ["1"], "expected": 1}, - {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, - {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, - { - "func": "bcrypt_hash", - "values": ["my_pass"], - "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, - {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, - {"func": "fail", "values": ["my_message"], "expect_raise": True}, - { - "func": "htpasswd", - "values": ["my_user", "my_pass"], - "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "is_boolean", "values": ["true"], "expected": True}, - {"func": "is_boolean", "values": ["false"], "expected": True}, - {"func": "is_number", "values": ["1"], "expected": True}, - {"func": "is_number", "values": ["1.1"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, - {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, - {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, - {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, - {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, - ] - - for test in tests: - print(test["func"], test) - func = render.funcs[test["func"]] - if test.get("expect_raise", False): - with pytest.raises(Exception): - func(*test["values"]) - elif test.get("expect_regex"): - r = func(*test["values"]) - assert re.match(test["expect_regex"], r) is not None - else: - r = func(*test["values"]) - assert r == test["expected"] diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_healthcheck.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_volumes.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_volumes.py deleted file mode 100644 index e0ae9a6953..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_volumes.py +++ /dev/null @@ -1,666 +0,0 @@ -import pytest - - -from render import Render -from formatter import get_hashed_name_for_volume - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_volume_invalid_type(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "invalid_type"}) - - -def test_add_volume_empty_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("", {"type": "tmpfs"}) - - -def test_add_volume_duplicate_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_storage("/some/path", {"type": "tmpfs"}) - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "tmpfs"}) - - -def test_add_volume_host_path_invalid_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_host_path_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path"} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_with_acl_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_mount(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_acl(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, - } - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test/acl", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "slave"}, - } - ] - - -def test_add_host_path_volume_mount_with_create_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_invalid_dataset_name(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_no_ix_volume_config(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume"} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_volume_mount(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_volume_mount_with_options(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = { - "type": "ix_volume", - "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, - } - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rslave"}, - } - ] - - -def test_cifs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_username(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_password(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_without_cifs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["verbose=true", "verbose=true"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["user=username"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": {"verbose": True}, - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": [{"verbose": True}], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_add_cifs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_cifs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["vers=3.0", "verbose=true"], - } - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "cifs", - "device": "//server/path", - "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_without_nfs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = { - "type": "nfs", - "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_add_nfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path"} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "nfs", - "device": ":/path", - "o": "addr=server,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_tmpfs_invalid_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_zero_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_invalid_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs"} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "tmpfs", - "target": "/some/path", - "read_only": False, - } - ] - - -def test_temporary_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "source": "test_temp_volume", - "type": "volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - - -def test_docker_volume_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume_missing_volume_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["volumes"] == {"test_volume": {}} - - -def test_anonymous_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} - ] - assert "volumes" not in output - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_not_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/validations.py b/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/nextcloud/1.4.15/README.md b/trains/stable/nextcloud/1.4.16/README.md similarity index 100% rename from trains/stable/nextcloud/1.4.15/README.md rename to trains/stable/nextcloud/1.4.16/README.md diff --git a/trains/stable/nextcloud/1.4.15/app.yaml b/trains/stable/nextcloud/1.4.16/app.yaml similarity index 94% rename from trains/stable/nextcloud/1.4.15/app.yaml rename to trains/stable/nextcloud/1.4.16/app.yaml index 63283fd48d..bb0473ec16 100644 --- a/trains/stable/nextcloud/1.4.15/app.yaml +++ b/trains/stable/nextcloud/1.4.16/app.yaml @@ -28,8 +28,8 @@ keywords: - http - web - php -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -66,4 +66,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/nextcloud title: Nextcloud train: stable -version: 1.4.15 +version: 1.4.16 diff --git a/trains/stable/nextcloud/1.4.15/ix_values.yaml b/trains/stable/nextcloud/1.4.16/ix_values.yaml similarity index 100% rename from trains/stable/nextcloud/1.4.15/ix_values.yaml rename to trains/stable/nextcloud/1.4.16/ix_values.yaml diff --git a/trains/stable/nextcloud/1.4.15/migrations/migrate_from_kubernetes b/trains/stable/nextcloud/1.4.16/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migrate_from_kubernetes rename to trains/stable/nextcloud/1.4.16/migrations/migrate_from_kubernetes diff --git a/trains/stable/nextcloud/1.4.15/migrations/migration_helpers/__init__.py b/trains/stable/nextcloud/1.4.16/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migration_helpers/__init__.py rename to trains/stable/nextcloud/1.4.16/migrations/migration_helpers/__init__.py diff --git a/trains/stable/nextcloud/1.4.15/migrations/migration_helpers/cpu.py b/trains/stable/nextcloud/1.4.16/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migration_helpers/cpu.py rename to trains/stable/nextcloud/1.4.16/migrations/migration_helpers/cpu.py diff --git a/trains/stable/nextcloud/1.4.15/migrations/migration_helpers/dns_config.py b/trains/stable/nextcloud/1.4.16/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migration_helpers/dns_config.py rename to trains/stable/nextcloud/1.4.16/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/nextcloud/1.4.15/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/nextcloud/1.4.16/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/nextcloud/1.4.16/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/nextcloud/1.4.15/migrations/migration_helpers/memory.py b/trains/stable/nextcloud/1.4.16/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migration_helpers/memory.py rename to trains/stable/nextcloud/1.4.16/migrations/migration_helpers/memory.py diff --git a/trains/stable/nextcloud/1.4.15/migrations/migration_helpers/resources.py b/trains/stable/nextcloud/1.4.16/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migration_helpers/resources.py rename to trains/stable/nextcloud/1.4.16/migrations/migration_helpers/resources.py diff --git a/trains/stable/nextcloud/1.4.15/migrations/migration_helpers/storage.py b/trains/stable/nextcloud/1.4.16/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/migrations/migration_helpers/storage.py rename to trains/stable/nextcloud/1.4.16/migrations/migration_helpers/storage.py diff --git a/trains/stable/nextcloud/1.4.15/questions.yaml b/trains/stable/nextcloud/1.4.16/questions.yaml similarity index 100% rename from trains/stable/nextcloud/1.4.15/questions.yaml rename to trains/stable/nextcloud/1.4.16/questions.yaml diff --git a/trains/stable/nextcloud/1.4.15/templates/docker-compose.yaml b/trains/stable/nextcloud/1.4.16/templates/docker-compose.yaml similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/docker-compose.yaml rename to trains/stable/nextcloud/1.4.16/templates/docker-compose.yaml diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/__init__.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/__init__.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/configs.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/configs.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/container.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/depends.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/depends.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/deploy.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/deploy.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/device.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/device.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/devices.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/dns.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/dns.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/environment.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/error.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/error.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/formatter.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/formatter.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/functions.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/functions.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/functions.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/functions.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/labels.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/labels.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/notes.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/notes.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/portal.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/portal.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/portals.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/portals.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/ports.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/ports.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/render.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/render.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/resources.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/resources.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/restart.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/restart.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/storage.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/storage.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/sysctls.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/__init__.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/__init__.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_build_image.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_build_image.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_configs.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_configs.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_depends.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_depends.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_dns.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_dns.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_formatter.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_formatter.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_labels.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_labels.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_notes.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_notes.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_portal.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_portal.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_ports.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_ports.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_render.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_render.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_resources.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_resources.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_restart.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/tests/test_restart.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/validations.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_mount.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_mount.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_mount_types.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_mount_types.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_sources.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_sources.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_types.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volume_types.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volumes.py b/trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/library/base_v2_0_21/volumes.py rename to trains/stable/nextcloud/1.4.16/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/nextcloud/1.4.15/templates/macros/nc.jinja.conf b/trains/stable/nextcloud/1.4.16/templates/macros/nc.jinja.conf similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/macros/nc.jinja.conf rename to trains/stable/nextcloud/1.4.16/templates/macros/nc.jinja.conf diff --git a/trains/stable/nextcloud/1.4.15/templates/macros/nc.jinja.sh b/trains/stable/nextcloud/1.4.16/templates/macros/nc.jinja.sh similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/macros/nc.jinja.sh rename to trains/stable/nextcloud/1.4.16/templates/macros/nc.jinja.sh diff --git a/trains/stable/nextcloud/1.4.15/templates/test_values/basic-values.yaml b/trains/stable/nextcloud/1.4.16/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/test_values/basic-values.yaml rename to trains/stable/nextcloud/1.4.16/templates/test_values/basic-values.yaml diff --git a/trains/stable/nextcloud/1.4.15/templates/test_values/https-values.yaml b/trains/stable/nextcloud/1.4.16/templates/test_values/https-values.yaml similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/test_values/https-values.yaml rename to trains/stable/nextcloud/1.4.16/templates/test_values/https-values.yaml diff --git a/trains/stable/nextcloud/1.4.15/templates/test_values/no-cron-values.yaml b/trains/stable/nextcloud/1.4.16/templates/test_values/no-cron-values.yaml similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/test_values/no-cron-values.yaml rename to trains/stable/nextcloud/1.4.16/templates/test_values/no-cron-values.yaml diff --git a/trains/stable/nextcloud/1.4.15/templates/test_values/same-vol-values.yaml b/trains/stable/nextcloud/1.4.16/templates/test_values/same-vol-values.yaml similarity index 100% rename from trains/stable/nextcloud/1.4.15/templates/test_values/same-vol-values.yaml rename to trains/stable/nextcloud/1.4.16/templates/test_values/same-vol-values.yaml diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/container.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/deps.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/devices.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/environment.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/validations.py b/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/photoprism/1.2.0/README.md b/trains/stable/photoprism/1.2.1/README.md similarity index 100% rename from trains/stable/photoprism/1.2.0/README.md rename to trains/stable/photoprism/1.2.1/README.md diff --git a/trains/stable/photoprism/1.2.0/app.yaml b/trains/stable/photoprism/1.2.1/app.yaml similarity index 91% rename from trains/stable/photoprism/1.2.0/app.yaml rename to trains/stable/photoprism/1.2.1/app.yaml index a847135121..c3ec80e880 100644 --- a/trains/stable/photoprism/1.2.0/app.yaml +++ b/trains/stable/photoprism/1.2.1/app.yaml @@ -22,8 +22,8 @@ keywords: - media - photos - image -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -42,4 +42,4 @@ sources: - https://photoprism.app/ title: Photoprism train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/trains/stable/photoprism/1.2.0/ix_values.yaml b/trains/stable/photoprism/1.2.1/ix_values.yaml similarity index 100% rename from trains/stable/photoprism/1.2.0/ix_values.yaml rename to trains/stable/photoprism/1.2.1/ix_values.yaml diff --git a/trains/stable/photoprism/1.2.0/migrations/migrate_from_kubernetes b/trains/stable/photoprism/1.2.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migrate_from_kubernetes rename to trains/stable/photoprism/1.2.1/migrations/migrate_from_kubernetes diff --git a/trains/stable/photoprism/1.2.0/migrations/migration_helpers/__init__.py b/trains/stable/photoprism/1.2.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migration_helpers/__init__.py rename to trains/stable/photoprism/1.2.1/migrations/migration_helpers/__init__.py diff --git a/trains/stable/photoprism/1.2.0/migrations/migration_helpers/cpu.py b/trains/stable/photoprism/1.2.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migration_helpers/cpu.py rename to trains/stable/photoprism/1.2.1/migrations/migration_helpers/cpu.py diff --git a/trains/stable/photoprism/1.2.0/migrations/migration_helpers/dns_config.py b/trains/stable/photoprism/1.2.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migration_helpers/dns_config.py rename to trains/stable/photoprism/1.2.1/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/photoprism/1.2.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/photoprism/1.2.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/photoprism/1.2.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/photoprism/1.2.0/migrations/migration_helpers/memory.py b/trains/stable/photoprism/1.2.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migration_helpers/memory.py rename to trains/stable/photoprism/1.2.1/migrations/migration_helpers/memory.py diff --git a/trains/stable/photoprism/1.2.0/migrations/migration_helpers/resources.py b/trains/stable/photoprism/1.2.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migration_helpers/resources.py rename to trains/stable/photoprism/1.2.1/migrations/migration_helpers/resources.py diff --git a/trains/stable/photoprism/1.2.0/migrations/migration_helpers/storage.py b/trains/stable/photoprism/1.2.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/photoprism/1.2.0/migrations/migration_helpers/storage.py rename to trains/stable/photoprism/1.2.1/migrations/migration_helpers/storage.py diff --git a/trains/stable/photoprism/1.2.0/questions.yaml b/trains/stable/photoprism/1.2.1/questions.yaml similarity index 100% rename from trains/stable/photoprism/1.2.0/questions.yaml rename to trains/stable/photoprism/1.2.1/questions.yaml diff --git a/trains/stable/photoprism/1.2.0/templates/docker-compose.yaml b/trains/stable/photoprism/1.2.1/templates/docker-compose.yaml similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/docker-compose.yaml rename to trains/stable/photoprism/1.2.1/templates/docker-compose.yaml diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/__init__.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/__init__.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/configs.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/configs.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/container.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/depends.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/depends.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/deploy.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/deploy.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/device.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/device.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/devices.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/dns.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/dns.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/environment.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/error.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/error.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/formatter.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/formatter.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/functions.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/functions.py similarity index 99% rename from trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/functions.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/functions.py index 47a2c1233a..7d082d8c46 100644 --- a/trains/stable/diskoverdata/1.4.1/templates/library/base_v2_0_31/functions.py +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -79,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/labels.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/labels.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/notes.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/notes.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/portal.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/portal.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/portals.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/portals.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/ports.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/ports.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/render.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/render.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/resources.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/resources.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/restart.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/restart.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/storage.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/storage.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/storage.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/storage.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/sysctls.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/sysctls.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/sysctls.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/sysctls.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_functions.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_functions.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_sysctls.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_sysctls.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_volumes.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_volumes.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py diff --git a/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/validations.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_types.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volumes.py b/trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/library/base_v2_0_32/volumes.py rename to trains/stable/photoprism/1.2.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/photoprism/1.2.0/templates/test_values/basic-values.yaml b/trains/stable/photoprism/1.2.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/test_values/basic-values.yaml rename to trains/stable/photoprism/1.2.1/templates/test_values/basic-values.yaml diff --git a/trains/stable/photoprism/1.2.0/templates/test_values/host-values.yaml b/trains/stable/photoprism/1.2.1/templates/test_values/host-values.yaml similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/test_values/host-values.yaml rename to trains/stable/photoprism/1.2.1/templates/test_values/host-values.yaml diff --git a/trains/stable/photoprism/1.2.0/templates/test_values/https-values.yaml b/trains/stable/photoprism/1.2.1/templates/test_values/https-values.yaml similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/test_values/https-values.yaml rename to trains/stable/photoprism/1.2.1/templates/test_values/https-values.yaml diff --git a/trains/stable/photoprism/1.2.0/templates/test_values/pass-values.yaml b/trains/stable/photoprism/1.2.1/templates/test_values/pass-values.yaml similarity index 100% rename from trains/stable/photoprism/1.2.0/templates/test_values/pass-values.yaml rename to trains/stable/photoprism/1.2.1/templates/test_values/pass-values.yaml diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/container.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/deps.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/devices.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/environment.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/validations.py b/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/pihole/1.2.0/README.md b/trains/stable/pihole/1.2.1/README.md similarity index 100% rename from trains/stable/pihole/1.2.0/README.md rename to trains/stable/pihole/1.2.1/README.md diff --git a/trains/stable/pihole/1.2.0/app.yaml b/trains/stable/pihole/1.2.1/app.yaml similarity index 93% rename from trains/stable/pihole/1.2.0/app.yaml rename to trains/stable/pihole/1.2.1/app.yaml index 6ba4776476..f7fbd40181 100644 --- a/trains/stable/pihole/1.2.0/app.yaml +++ b/trains/stable/pihole/1.2.1/app.yaml @@ -33,8 +33,8 @@ icon: https://media.sys.truenas.net/apps/pihole/icons/icon.png keywords: - networking - dns -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -53,4 +53,4 @@ sources: - https://github.com/truenas/charts/tree/master/charts/pihole title: Pi-hole train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/trains/stable/pihole/1.2.0/ix_values.yaml b/trains/stable/pihole/1.2.1/ix_values.yaml similarity index 100% rename from trains/stable/pihole/1.2.0/ix_values.yaml rename to trains/stable/pihole/1.2.1/ix_values.yaml diff --git a/trains/stable/pihole/1.2.0/migrations/migrate_from_kubernetes b/trains/stable/pihole/1.2.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migrate_from_kubernetes rename to trains/stable/pihole/1.2.1/migrations/migrate_from_kubernetes diff --git a/trains/stable/pihole/1.2.0/migrations/migration_helpers/__init__.py b/trains/stable/pihole/1.2.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migration_helpers/__init__.py rename to trains/stable/pihole/1.2.1/migrations/migration_helpers/__init__.py diff --git a/trains/stable/pihole/1.2.0/migrations/migration_helpers/cpu.py b/trains/stable/pihole/1.2.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migration_helpers/cpu.py rename to trains/stable/pihole/1.2.1/migrations/migration_helpers/cpu.py diff --git a/trains/stable/pihole/1.2.0/migrations/migration_helpers/dns_config.py b/trains/stable/pihole/1.2.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migration_helpers/dns_config.py rename to trains/stable/pihole/1.2.1/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/pihole/1.2.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/pihole/1.2.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/pihole/1.2.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/pihole/1.2.0/migrations/migration_helpers/memory.py b/trains/stable/pihole/1.2.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migration_helpers/memory.py rename to trains/stable/pihole/1.2.1/migrations/migration_helpers/memory.py diff --git a/trains/stable/pihole/1.2.0/migrations/migration_helpers/resources.py b/trains/stable/pihole/1.2.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migration_helpers/resources.py rename to trains/stable/pihole/1.2.1/migrations/migration_helpers/resources.py diff --git a/trains/stable/pihole/1.2.0/migrations/migration_helpers/storage.py b/trains/stable/pihole/1.2.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/pihole/1.2.0/migrations/migration_helpers/storage.py rename to trains/stable/pihole/1.2.1/migrations/migration_helpers/storage.py diff --git a/trains/stable/pihole/1.2.0/questions.yaml b/trains/stable/pihole/1.2.1/questions.yaml similarity index 100% rename from trains/stable/pihole/1.2.0/questions.yaml rename to trains/stable/pihole/1.2.1/questions.yaml diff --git a/trains/stable/pihole/1.2.0/templates/docker-compose.yaml b/trains/stable/pihole/1.2.1/templates/docker-compose.yaml similarity index 100% rename from trains/stable/pihole/1.2.0/templates/docker-compose.yaml rename to trains/stable/pihole/1.2.1/templates/docker-compose.yaml diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/__init__.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/__init__.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/configs.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/configs.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/container.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/depends.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/depends.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/deploy.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/deploy.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/device.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/device.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/devices.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/dns.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/dns.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/environment.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/error.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/error.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/formatter.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/formatter.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/functions.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/functions.py similarity index 63% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/functions.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/functions.py index a8799c3963..7d082d8c46 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/functions.py +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -9,8 +10,10 @@ try: from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource except ImportError: from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource class Functions: @@ -77,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} @@ -85,10 +88,42 @@ def _merge_dicts(self, *dicts): merged_dict.update(dictionary) return merged_dict - def _disallow_chars(self, string, chars, key): + def _disallow_chars(self, string: str, chars: list[str], key: str): for char in chars: if char in string: raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") def func_map(self): # TODO: Check what is no longer used and remove @@ -108,4 +143,7 @@ def func_map(self): "must_match_regex": self._must_match_regex, "secure_string": self._secure_string, "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, } diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/labels.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/labels.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/notes.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/notes.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/portal.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/portal.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/portals.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/portals.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/ports.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/ports.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/render.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/render.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/resources.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/resources.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/restart.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/restart.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/storage.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/storage.py similarity index 87% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/storage.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/storage.py +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/sysctls.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_functions.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_functions.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_functions.py +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_volumes.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_volumes.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/validations.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_types.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volumes.py b/trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/pihole/1.2.0/templates/library/base_v2_0_32/volumes.py rename to trains/stable/pihole/1.2.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/pihole/1.2.0/templates/test_values/basic-values.yaml b/trains/stable/pihole/1.2.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/pihole/1.2.0/templates/test_values/basic-values.yaml rename to trains/stable/pihole/1.2.1/templates/test_values/basic-values.yaml diff --git a/trains/stable/pihole/1.2.0/templates/test_values/dhcp-values.yaml b/trains/stable/pihole/1.2.1/templates/test_values/dhcp-values.yaml similarity index 100% rename from trains/stable/pihole/1.2.0/templates/test_values/dhcp-values.yaml rename to trains/stable/pihole/1.2.1/templates/test_values/dhcp-values.yaml diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/container.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/container.py deleted file mode 100644 index 1994caf704..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/container.py +++ /dev/null @@ -1,300 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = self._grace_period - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_devices(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/deps.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/deps.py deleted file mode 100644 index fdf69b2875..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/deps.py +++ /dev/null @@ -1,443 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod): - print(f"Changing permissions to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid): - print(f"Changing ownership to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/devices.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/devices.py deleted file mode 100644 index c9f8cf633e..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/devices.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/environment.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/functions.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/functions.py deleted file mode 100644 index a8799c3963..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/functions.py +++ /dev/null @@ -1,111 +0,0 @@ -import re -import bcrypt -import secrets -from base64 import b64encode -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError -except ImportError: - from error import RenderError - - -class Functions: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def _bcrypt_hash(self, password): - hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") - return hashed - - def _htpasswd(self, username, password): - hashed = self._bcrypt_hash(password) - return username + ":" + hashed - - def _secure_string(self, length): - return secrets.token_urlsafe(length) - - def _basic_auth(self, username, password): - return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") - - def _basic_auth_header(self, username, password): - return f"Basic {self._basic_auth(username, password)}" - - def _fail(self, message): - raise RenderError(message) - - def _camel_case(self, string): - return string.title() - - def _auto_cast(self, value): - try: - return int(value) - except ValueError: - pass - - try: - return float(value) - except ValueError: - pass - - if value.lower() in ["true", "false"]: - return value.lower() == "true" - - return value - - def _match_regex(self, value, regex): - if not re.match(regex, value): - return False - return True - - def _must_match_regex(self, value, regex): - if not self._match_regex(value, regex): - raise RenderError(f"Expected [{value}] to match [{regex}]") - return value - - def _is_boolean(self, string): - return string.lower() in ["true", "false"] - - def _is_number(self, string): - try: - float(string) - return True - except ValueError: - return False - - def _copy_dict(self, dict): - return dict.copy() - - def _merge_dicts(self, *dicts): - merged_dict = {} - for dictionary in dicts: - merged_dict.update(dictionary) - return merged_dict - - def _disallow_chars(self, string, chars, key): - for char in chars: - if char in string: - raise RenderError(f"Disallowed character [{char}] in [{key}]") - - def func_map(self): - # TODO: Check what is no longer used and remove - return { - "auto_cast": self._auto_cast, - "basic_auth_header": self._basic_auth_header, - "basic_auth": self._basic_auth, - "bcrypt_hash": self._bcrypt_hash, - "camel_case": self._camel_case, - "copy_dict": self._copy_dict, - "fail": self._fail, - "htpasswd": self._htpasswd, - "is_boolean": self._is_boolean, - "is_number": self._is_number, - "match_regex": self._match_regex, - "merge_dicts": self._merge_dicts, - "must_match_regex": self._must_match_regex, - "secure_string": self._secure_string, - "disallow_chars": self._disallow_chars, - } diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/healthcheck.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/healthcheck.py deleted file mode 100644 index a54f3f3133..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep -q "200 OK"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/storage.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/storage.py deleted file mode 100644 index 3e5b629790..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/storage.py +++ /dev/null @@ -1,106 +0,0 @@ -from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .validations import valid_fs_path_or_raise - from .volume_mount import VolumeMount -except ImportError: - from error import RenderError - from validations import valid_fs_path_or_raise - from volume_mount import VolumeMount - - -class IxStorageTmpfsConfig(TypedDict): - size: NotRequired[int] - mode: NotRequired[str] - - -class AclConfig(TypedDict, total=False): - path: str - - -class IxStorageHostPathConfig(TypedDict): - path: NotRequired[str] # Either this or acl.path must be set - acl_enable: NotRequired[bool] - acl: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageIxVolumeConfig(TypedDict): - dataset_name: str - acl_enable: NotRequired[bool] - acl_entries: NotRequired[AclConfig] - create_host_path: NotRequired[bool] - propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] - auto_permissions: NotRequired[bool] # Only when acl_enable is false - - -class IxStorageVolumeConfig(TypedDict): - volume_name: NotRequired[str] - nocopy: NotRequired[bool] - auto_permissions: NotRequired[bool] - - -class IxStorageNfsConfig(TypedDict): - server: str - path: str - options: NotRequired[list[str]] - - -class IxStorageCifsConfig(TypedDict): - server: str - path: str - username: str - password: str - domain: NotRequired[str] - options: NotRequired[list[str]] - - -IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] -IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] -IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] - - -class IxStorage(TypedDict): - type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] - read_only: NotRequired[bool] - - ix_volume_config: NotRequired[IxStorageIxVolumeConfig] - host_path_config: NotRequired[IxStorageHostPathConfig] - tmpfs_config: NotRequired[IxStorageTmpfsConfig] - volume_config: NotRequired[IxStorageVolumeConfig] - nfs_config: NotRequired[IxStorageNfsConfig] - cifs_config: NotRequired[IxStorageCifsConfig] - - -class Storage: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._volume_mounts: set[VolumeMount] = set() - - def add(self, mount_path: str, config: "IxStorage"): - mount_path = valid_fs_path_or_raise(mount_path) - if mount_path in [m.mount_path for m in self._volume_mounts]: - raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") - - volume_mount = VolumeMount(self._render_instance, mount_path, config) - self._volume_mounts.add(volume_mount) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - cfg: "IxStorage" = { - "type": "host_path", - "read_only": read_only, - "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, - } - self.add(mount_path, cfg) - - def has_mounts(self) -> bool: - return bool(self._volume_mounts) - - def render(self): - return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_container.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_container.py deleted file mode 100644 index 35f26f43af..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_container.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == 10 - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_deps.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_deps.py deleted file mode 100644 index 81e399c85d..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_device.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_environment.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_functions.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_functions.py deleted file mode 100644 index a75e7c4084..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_functions.py +++ /dev/null @@ -1,65 +0,0 @@ -import re -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_funcs(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - tests = [ - {"func": "auto_cast", "values": ["1"], "expected": 1}, - {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, - {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, - { - "func": "bcrypt_hash", - "values": ["my_pass"], - "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, - {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, - {"func": "fail", "values": ["my_message"], "expect_raise": True}, - { - "func": "htpasswd", - "values": ["my_user", "my_pass"], - "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", - }, - {"func": "is_boolean", "values": ["true"], "expected": True}, - {"func": "is_boolean", "values": ["false"], "expected": True}, - {"func": "is_number", "values": ["1"], "expected": True}, - {"func": "is_number", "values": ["1.1"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, - {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, - {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, - {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, - {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, - {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, - ] - - for test in tests: - print(test["func"], test) - func = render.funcs[test["func"]] - if test.get("expect_raise", False): - with pytest.raises(Exception): - func(*test["values"]) - elif test.get("expect_regex"): - r = func(*test["values"]) - assert re.match(test["expect_regex"], r) is not None - else: - r = func(*test["values"]) - assert r == test["expected"] diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_healthcheck.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_healthcheck.py deleted file mode 100644 index 8267b986b4..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep -q "200 OK"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_volumes.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_volumes.py deleted file mode 100644 index e0ae9a6953..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_volumes.py +++ /dev/null @@ -1,666 +0,0 @@ -import pytest - - -from render import Render -from formatter import get_hashed_name_for_volume - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_volume_invalid_type(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "invalid_type"}) - - -def test_add_volume_empty_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_storage("", {"type": "tmpfs"}) - - -def test_add_volume_duplicate_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_storage("/some/path", {"type": "tmpfs"}) - with pytest.raises(Exception): - c1.add_storage("/some/path", {"type": "tmpfs"}) - - -def test_add_volume_host_path_invalid_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_host_path_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path"} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_with_acl_no_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", host_path_config) - - -def test_add_host_path_volume_mount(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_acl(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = { - "type": "host_path", - "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, - } - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test/acl", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_propagation(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "slave"}, - } - ] - - -def test_add_host_path_volume_mount_with_create_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rprivate"}, - } - ] - - -def test_add_host_path_volume_mount_with_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} - c1.add_storage("/some/path", host_path_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_invalid_dataset_name(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_no_ix_volume_config(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume"} - with pytest.raises(Exception): - c1.add_storage("/some/path", ix_volume_config) - - -def test_add_ix_volume_volume_mount(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_ix_volume_volume_mount_with_options(mock_values): - mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - ix_volume_config = { - "type": "ix_volume", - "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, - } - c1.add_storage("/some/path", ix_volume_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/mnt/test", - "target": "/some/path", - "read_only": False, - "bind": {"create_host_path": True, "propagation": "rslave"}, - } - ] - - -def test_cifs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_username(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_missing_password(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_without_cifs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = {"type": "cifs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["verbose=true", "verbose=true"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["user=username"], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": {"verbose": True}, - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_cifs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_config = { - "type": "cifs", - "cifs_config": { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": [{"verbose": True}], - }, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", cifs_config) - - -def test_add_cifs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_cifs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - cifs_inner_config = { - "server": "server", - "path": "/path", - "username": "user", - "password": "pas$word", - "options": ["vers=3.0", "verbose=true"], - } - cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} - c1.add_storage("/some/path", cifs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "cifs", - "device": "//server/path", - "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_missing_server(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_missing_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_without_nfs_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs"} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_duplicate_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = { - "type": "nfs", - "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, - } - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_disallowed_option(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_nfs_volume_invalid_options2(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} - with pytest.raises(Exception): - c1.add_storage("/some/path", nfs_config) - - -def test_add_nfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path"} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_nfs_volume_with_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} - nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} - c1.add_storage("/some/path", nfs_config) - output = render.render() - vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) - assert output["volumes"] == { - vol_name: { - "driver_opts": { - "type": "nfs", - "device": ":/path", - "o": "addr=server,verbose=true,vers=3.0", - } - } - } - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} - ] - - -def test_tmpfs_invalid_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_zero_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_invalid_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_tmpfs_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "tmpfs"} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "tmpfs", - "target": "/some/path", - "read_only": False, - } - ] - - -def test_temporary_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "source": "test_temp_volume", - "type": "volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - - -def test_docker_volume_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume_missing_volume_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} - with pytest.raises(Exception): - c1.add_storage("/some/path", vol_config) - - -def test_docker_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/some/path", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["volumes"] == {"test_volume": {}} - - -def test_anonymous_volume(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} - c1.add_storage("/some/path", vol_config) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} - ] - assert "volumes" not in output - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_not_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": False, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] - - -def test_add_docker_socket_mount_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/some/path", - "read_only": True, - "bind": {"create_host_path": False, "propagation": "rprivate"}, - } - ] diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/validations.py b/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/validations.py deleted file mode 100644 index 57e039917b..0000000000 --- a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/validations.py +++ /dev/null @@ -1,203 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/plex/1.1.4/README.md b/trains/stable/plex/1.1.5/README.md similarity index 100% rename from trains/stable/plex/1.1.4/README.md rename to trains/stable/plex/1.1.5/README.md diff --git a/trains/stable/plex/1.1.4/app.yaml b/trains/stable/plex/1.1.5/app.yaml similarity index 91% rename from trains/stable/plex/1.1.4/app.yaml rename to trains/stable/plex/1.1.5/app.yaml index 3019d5a922..6749a87e05 100644 --- a/trains/stable/plex/1.1.4/app.yaml +++ b/trains/stable/plex/1.1.5/app.yaml @@ -27,8 +27,8 @@ keywords: - series - tv - streaming -lib_version: 2.0.21 -lib_version_hash: e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -48,4 +48,4 @@ sources: - https://hub.docker.com/r/plexinc/pms-docker title: Plex train: stable -version: 1.1.4 +version: 1.1.5 diff --git a/trains/stable/plex/1.1.4/ix_values.yaml b/trains/stable/plex/1.1.5/ix_values.yaml similarity index 100% rename from trains/stable/plex/1.1.4/ix_values.yaml rename to trains/stable/plex/1.1.5/ix_values.yaml diff --git a/trains/stable/plex/1.1.4/migrations/__init__.py b/trains/stable/plex/1.1.5/migrations/__init__.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/__init__.py rename to trains/stable/plex/1.1.5/migrations/__init__.py diff --git a/trains/stable/plex/1.1.4/migrations/migrate_from_kubernetes b/trains/stable/plex/1.1.5/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migrate_from_kubernetes rename to trains/stable/plex/1.1.5/migrations/migrate_from_kubernetes diff --git a/trains/stable/plex/1.1.4/migrations/migration_helpers/__init__.py b/trains/stable/plex/1.1.5/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migration_helpers/__init__.py rename to trains/stable/plex/1.1.5/migrations/migration_helpers/__init__.py diff --git a/trains/stable/plex/1.1.4/migrations/migration_helpers/cpu.py b/trains/stable/plex/1.1.5/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migration_helpers/cpu.py rename to trains/stable/plex/1.1.5/migrations/migration_helpers/cpu.py diff --git a/trains/stable/plex/1.1.4/migrations/migration_helpers/dns_config.py b/trains/stable/plex/1.1.5/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migration_helpers/dns_config.py rename to trains/stable/plex/1.1.5/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/plex/1.1.4/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/plex/1.1.5/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/plex/1.1.5/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/plex/1.1.4/migrations/migration_helpers/memory.py b/trains/stable/plex/1.1.5/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migration_helpers/memory.py rename to trains/stable/plex/1.1.5/migrations/migration_helpers/memory.py diff --git a/trains/stable/plex/1.1.4/migrations/migration_helpers/resources.py b/trains/stable/plex/1.1.5/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migration_helpers/resources.py rename to trains/stable/plex/1.1.5/migrations/migration_helpers/resources.py diff --git a/trains/stable/plex/1.1.4/migrations/migration_helpers/storage.py b/trains/stable/plex/1.1.5/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/plex/1.1.4/migrations/migration_helpers/storage.py rename to trains/stable/plex/1.1.5/migrations/migration_helpers/storage.py diff --git a/trains/stable/plex/1.1.4/questions.yaml b/trains/stable/plex/1.1.5/questions.yaml similarity index 100% rename from trains/stable/plex/1.1.4/questions.yaml rename to trains/stable/plex/1.1.5/questions.yaml diff --git a/trains/stable/plex/1.1.4/templates/docker-compose.yaml b/trains/stable/plex/1.1.5/templates/docker-compose.yaml similarity index 100% rename from trains/stable/plex/1.1.4/templates/docker-compose.yaml rename to trains/stable/plex/1.1.5/templates/docker-compose.yaml diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/__init__.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/__init__.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/configs.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/configs.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/container.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/depends.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/depends.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/deploy.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/deploy.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/device.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/device.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/devices.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/dns.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/dns.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/environment.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/error.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/error.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/formatter.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/formatter.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/functions.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/functions.py similarity index 63% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/functions.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/functions.py index a8799c3963..7d082d8c46 100644 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/functions.py +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -9,8 +10,10 @@ try: from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource except ImportError: from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource class Functions: @@ -77,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} @@ -85,10 +88,42 @@ def _merge_dicts(self, *dicts): merged_dict.update(dictionary) return merged_dict - def _disallow_chars(self, string, chars, key): + def _disallow_chars(self, string: str, chars: list[str], key: str): for char in chars: if char in string: raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") def func_map(self): # TODO: Check what is no longer used and remove @@ -108,4 +143,7 @@ def func_map(self): "must_match_regex": self._must_match_regex, "secure_string": self._secure_string, "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, } diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/labels.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/labels.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/notes.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/notes.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/portal.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/portal.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/portals.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/portals.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/ports.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/ports.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/render.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/render.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/resources.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/resources.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/restart.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/restart.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/storage.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/storage.py similarity index 87% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/storage.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/storage.py +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/sysctls.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/__init__.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/__init__.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_build_image.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_build_image.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_configs.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_configs.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_depends.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_depends.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_dns.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_dns.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_formatter.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_formatter.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_functions.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_functions.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_functions.py +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_labels.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_labels.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_notes.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_notes.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_portal.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_portal.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_ports.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_ports.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_render.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_render.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_resources.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_resources.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_restart.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/tests/test_restart.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_sysctls.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_volumes.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_volumes.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/validations.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_mount.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_mount.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_mount_types.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_mount_types.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_sources.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_sources.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_types.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volume_types.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volumes.py b/trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/plex/1.1.4/templates/library/base_v2_0_21/volumes.py rename to trains/stable/plex/1.1.5/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/plex/1.1.4/templates/test_values/basic-values.yaml b/trains/stable/plex/1.1.5/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/plex/1.1.4/templates/test_values/basic-values.yaml rename to trains/stable/plex/1.1.5/templates/test_values/basic-values.yaml diff --git a/trains/stable/plex/1.1.4/templates/test_values/hostnet-values.yaml b/trains/stable/plex/1.1.5/templates/test_values/hostnet-values.yaml similarity index 100% rename from trains/stable/plex/1.1.4/templates/test_values/hostnet-values.yaml rename to trains/stable/plex/1.1.5/templates/test_values/hostnet-values.yaml diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/container.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/deps.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/devices.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/environment.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/validations.py b/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/prometheus/1.2.0/README.md b/trains/stable/prometheus/1.2.1/README.md similarity index 100% rename from trains/stable/prometheus/1.2.0/README.md rename to trains/stable/prometheus/1.2.1/README.md diff --git a/trains/stable/prometheus/1.2.0/app.yaml b/trains/stable/prometheus/1.2.1/app.yaml similarity index 86% rename from trains/stable/prometheus/1.2.0/app.yaml rename to trains/stable/prometheus/1.2.1/app.yaml index 00ab5ce03f..698eef10eb 100644 --- a/trains/stable/prometheus/1.2.0/app.yaml +++ b/trains/stable/prometheus/1.2.1/app.yaml @@ -9,8 +9,8 @@ icon: https://media.sys.truenas.net/apps/prometheus/icons/icon.png keywords: - metrics - prometheus -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -30,4 +30,4 @@ sources: - https://prometheus.io title: Prometheus train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/trains/stable/prometheus/1.2.0/ix_values.yaml b/trains/stable/prometheus/1.2.1/ix_values.yaml similarity index 100% rename from trains/stable/prometheus/1.2.0/ix_values.yaml rename to trains/stable/prometheus/1.2.1/ix_values.yaml diff --git a/trains/stable/prometheus/1.2.0/migrations/migrate_from_kubernetes b/trains/stable/prometheus/1.2.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migrate_from_kubernetes rename to trains/stable/prometheus/1.2.1/migrations/migrate_from_kubernetes diff --git a/trains/stable/prometheus/1.2.0/migrations/migration_helpers/__init__.py b/trains/stable/prometheus/1.2.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migration_helpers/__init__.py rename to trains/stable/prometheus/1.2.1/migrations/migration_helpers/__init__.py diff --git a/trains/stable/prometheus/1.2.0/migrations/migration_helpers/cpu.py b/trains/stable/prometheus/1.2.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migration_helpers/cpu.py rename to trains/stable/prometheus/1.2.1/migrations/migration_helpers/cpu.py diff --git a/trains/stable/prometheus/1.2.0/migrations/migration_helpers/dns_config.py b/trains/stable/prometheus/1.2.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migration_helpers/dns_config.py rename to trains/stable/prometheus/1.2.1/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/prometheus/1.2.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/prometheus/1.2.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/prometheus/1.2.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/prometheus/1.2.0/migrations/migration_helpers/memory.py b/trains/stable/prometheus/1.2.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migration_helpers/memory.py rename to trains/stable/prometheus/1.2.1/migrations/migration_helpers/memory.py diff --git a/trains/stable/prometheus/1.2.0/migrations/migration_helpers/resources.py b/trains/stable/prometheus/1.2.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migration_helpers/resources.py rename to trains/stable/prometheus/1.2.1/migrations/migration_helpers/resources.py diff --git a/trains/stable/prometheus/1.2.0/migrations/migration_helpers/storage.py b/trains/stable/prometheus/1.2.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/prometheus/1.2.0/migrations/migration_helpers/storage.py rename to trains/stable/prometheus/1.2.1/migrations/migration_helpers/storage.py diff --git a/trains/stable/prometheus/1.2.0/questions.yaml b/trains/stable/prometheus/1.2.1/questions.yaml similarity index 100% rename from trains/stable/prometheus/1.2.0/questions.yaml rename to trains/stable/prometheus/1.2.1/questions.yaml diff --git a/trains/stable/prometheus/1.2.0/templates/docker-compose.yaml b/trains/stable/prometheus/1.2.1/templates/docker-compose.yaml similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/docker-compose.yaml rename to trains/stable/prometheus/1.2.1/templates/docker-compose.yaml diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/__init__.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/__init__.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/configs.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/configs.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/container.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/depends.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/depends.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/deploy.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/deploy.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/device.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/device.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/devices.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/dns.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/dns.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/environment.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/error.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/error.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/formatter.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/formatter.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/functions.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/functions.py similarity index 63% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/functions.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/functions.py index a8799c3963..7d082d8c46 100644 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/functions.py +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/functions.py @@ -1,4 +1,5 @@ import re +import copy import bcrypt import secrets from base64 import b64encode @@ -9,8 +10,10 @@ try: from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource except ImportError: from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource class Functions: @@ -77,7 +80,7 @@ def _is_number(self, string): return False def _copy_dict(self, dict): - return dict.copy() + return copy.deepcopy(dict) def _merge_dicts(self, *dicts): merged_dict = {} @@ -85,10 +88,42 @@ def _merge_dicts(self, *dicts): merged_dict.update(dictionary) return merged_dict - def _disallow_chars(self, string, chars, key): + def _disallow_chars(self, string: str, chars: list[str], key: str): for char in chars: if char in string: raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") def func_map(self): # TODO: Check what is no longer used and remove @@ -108,4 +143,7 @@ def func_map(self): "must_match_regex": self._must_match_regex, "secure_string": self._secure_string, "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, } diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/labels.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/labels.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/notes.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/notes.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/portal.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/portal.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/portals.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/portals.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/ports.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/ports.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/render.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/render.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/resources.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/resources.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/restart.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/restart.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/storage.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/storage.py similarity index 87% rename from trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/storage.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/trains/enterprise/asigra-ds-system/1.0.15/templates/library/base_v2_0_21/storage.py +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/sysctls.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_functions.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_functions.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_functions.py +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_volumes.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_volumes.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/trains/stable/home-assistant/1.3.4/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/validations.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_types.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volumes.py b/trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/library/base_v2_0_32/volumes.py rename to trains/stable/prometheus/1.2.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/prometheus/1.2.0/templates/macros/init.sh b/trains/stable/prometheus/1.2.1/templates/macros/init.sh similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/macros/init.sh rename to trains/stable/prometheus/1.2.1/templates/macros/init.sh diff --git a/trains/stable/prometheus/1.2.0/templates/test_values/basic-values.yaml b/trains/stable/prometheus/1.2.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/test_values/basic-values.yaml rename to trains/stable/prometheus/1.2.1/templates/test_values/basic-values.yaml diff --git a/trains/stable/prometheus/1.2.0/templates/test_values/hostnet-values.yaml b/trains/stable/prometheus/1.2.1/templates/test_values/hostnet-values.yaml similarity index 100% rename from trains/stable/prometheus/1.2.0/templates/test_values/hostnet-values.yaml rename to trains/stable/prometheus/1.2.1/templates/test_values/hostnet-values.yaml diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/container.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/deps.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/devices.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/environment.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/validations.py b/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/storj/1.2.0/README.md b/trains/stable/storj/1.2.1/README.md similarity index 100% rename from trains/stable/storj/1.2.0/README.md rename to trains/stable/storj/1.2.1/README.md diff --git a/trains/stable/storj/1.2.0/app.yaml b/trains/stable/storj/1.2.1/app.yaml similarity index 89% rename from trains/stable/storj/1.2.0/app.yaml rename to trains/stable/storj/1.2.1/app.yaml index ae28ba5bf5..79c16e3f44 100644 --- a/trains/stable/storj/1.2.0/app.yaml +++ b/trains/stable/storj/1.2.1/app.yaml @@ -18,8 +18,8 @@ keywords: - networking - financial - file-sharing -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -37,4 +37,4 @@ sources: - https://www.storj.io title: Storj train: stable -version: 1.2.0 +version: 1.2.1 diff --git a/trains/stable/storj/1.2.0/ix_values.yaml b/trains/stable/storj/1.2.1/ix_values.yaml similarity index 100% rename from trains/stable/storj/1.2.0/ix_values.yaml rename to trains/stable/storj/1.2.1/ix_values.yaml diff --git a/trains/stable/storj/1.2.0/migrations/migrate_from_kubernetes b/trains/stable/storj/1.2.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migrate_from_kubernetes rename to trains/stable/storj/1.2.1/migrations/migrate_from_kubernetes diff --git a/trains/stable/storj/1.2.0/migrations/migration_helpers/__init__.py b/trains/stable/storj/1.2.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migration_helpers/__init__.py rename to trains/stable/storj/1.2.1/migrations/migration_helpers/__init__.py diff --git a/trains/stable/storj/1.2.0/migrations/migration_helpers/cpu.py b/trains/stable/storj/1.2.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migration_helpers/cpu.py rename to trains/stable/storj/1.2.1/migrations/migration_helpers/cpu.py diff --git a/trains/stable/storj/1.2.0/migrations/migration_helpers/dns_config.py b/trains/stable/storj/1.2.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migration_helpers/dns_config.py rename to trains/stable/storj/1.2.1/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/storj/1.2.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/storj/1.2.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/storj/1.2.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/storj/1.2.0/migrations/migration_helpers/memory.py b/trains/stable/storj/1.2.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migration_helpers/memory.py rename to trains/stable/storj/1.2.1/migrations/migration_helpers/memory.py diff --git a/trains/stable/storj/1.2.0/migrations/migration_helpers/resources.py b/trains/stable/storj/1.2.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migration_helpers/resources.py rename to trains/stable/storj/1.2.1/migrations/migration_helpers/resources.py diff --git a/trains/stable/storj/1.2.0/migrations/migration_helpers/storage.py b/trains/stable/storj/1.2.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/storj/1.2.0/migrations/migration_helpers/storage.py rename to trains/stable/storj/1.2.1/migrations/migration_helpers/storage.py diff --git a/trains/stable/storj/1.2.0/questions.yaml b/trains/stable/storj/1.2.1/questions.yaml similarity index 100% rename from trains/stable/storj/1.2.0/questions.yaml rename to trains/stable/storj/1.2.1/questions.yaml diff --git a/trains/stable/storj/1.2.0/templates/docker-compose.yaml b/trains/stable/storj/1.2.1/templates/docker-compose.yaml similarity index 100% rename from trains/stable/storj/1.2.0/templates/docker-compose.yaml rename to trains/stable/storj/1.2.1/templates/docker-compose.yaml diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/__init__.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/__init__.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/configs.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/configs.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/container.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/depends.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/depends.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/deploy.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/deploy.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/device.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/device.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/devices.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/dns.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/dns.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/environment.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/error.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/error.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/formatter.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/formatter.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/functions.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/functions.py new file mode 100644 index 0000000000..7d082d8c46 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/functions.py @@ -0,0 +1,149 @@ +import re +import copy +import bcrypt +import secrets +from base64 import b64encode +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource +except ImportError: + from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource + + +class Functions: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def _bcrypt_hash(self, password): + hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + return hashed + + def _htpasswd(self, username, password): + hashed = self._bcrypt_hash(password) + return username + ":" + hashed + + def _secure_string(self, length): + return secrets.token_urlsafe(length) + + def _basic_auth(self, username, password): + return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") + + def _basic_auth_header(self, username, password): + return f"Basic {self._basic_auth(username, password)}" + + def _fail(self, message): + raise RenderError(message) + + def _camel_case(self, string): + return string.title() + + def _auto_cast(self, value): + try: + return int(value) + except ValueError: + pass + + try: + return float(value) + except ValueError: + pass + + if value.lower() in ["true", "false"]: + return value.lower() == "true" + + return value + + def _match_regex(self, value, regex): + if not re.match(regex, value): + return False + return True + + def _must_match_regex(self, value, regex): + if not self._match_regex(value, regex): + raise RenderError(f"Expected [{value}] to match [{regex}]") + return value + + def _is_boolean(self, string): + return string.lower() in ["true", "false"] + + def _is_number(self, string): + try: + float(string) + return True + except ValueError: + return False + + def _copy_dict(self, dict): + return copy.deepcopy(dict) + + def _merge_dicts(self, *dicts): + merged_dict = {} + for dictionary in dicts: + merged_dict.update(dictionary) + return merged_dict + + def _disallow_chars(self, string: str, chars: list[str], key: str): + for char in chars: + if char in string: + raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") + + def func_map(self): + # TODO: Check what is no longer used and remove + return { + "auto_cast": self._auto_cast, + "basic_auth_header": self._basic_auth_header, + "basic_auth": self._basic_auth, + "bcrypt_hash": self._bcrypt_hash, + "camel_case": self._camel_case, + "copy_dict": self._copy_dict, + "fail": self._fail, + "htpasswd": self._htpasswd, + "is_boolean": self._is_boolean, + "is_number": self._is_number, + "match_regex": self._match_regex, + "merge_dicts": self._merge_dicts, + "must_match_regex": self._must_match_regex, + "secure_string": self._secure_string, + "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, + } diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/labels.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/labels.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/notes.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/notes.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/portal.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/portal.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/portals.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/portals.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/ports.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/ports.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/render.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/render.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/resources.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/resources.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/restart.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/restart.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/storage.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/storage.py similarity index 87% rename from trains/stable/emby/1.2.3/templates/library/base_v2_0_21/storage.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/storage.py index 3e5b629790..e697ba902a 100644 --- a/trains/stable/emby/1.2.3/templates/library/base_v2_0_21/storage.py +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/storage.py @@ -91,7 +91,8 @@ def add(self, mount_path: str, config: "IxStorage"): volume_mount = VolumeMount(self._render_instance, mount_path, config) self._volume_mounts.add(volume_mount) - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) cfg: "IxStorage" = { "type": "host_path", "read_only": read_only, @@ -99,6 +100,15 @@ def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/ } self.add(mount_path, cfg) + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + def has_mounts(self) -> bool: return bool(self._volume_mounts) diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/sysctls.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_functions.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py similarity index 68% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_functions.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py index a75e7c4084..0ea3b57d18 100644 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_functions.py +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_functions.py @@ -18,6 +18,7 @@ def mock_values(): def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() @@ -49,6 +50,28 @@ def test_funcs(mock_values): {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, ] for test in tests: diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_volumes.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py similarity index 99% rename from trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_volumes.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py index e0ae9a6953..aef0d39481 100644 --- a/trains/stable/minio/1.2.1/templates/library/base_v2_0_21/tests/test_volumes.py +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/tests/test_volumes.py @@ -619,7 +619,7 @@ def test_add_docker_socket(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -636,7 +636,7 @@ def test_add_docker_socket_not_read_only(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(read_only=False) + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { @@ -653,7 +653,7 @@ def test_add_docker_socket_mount_path(mock_values): render = Render(mock_values) c1 = render.add_container("test_container", "test_image") c1.healthcheck.disable() - c1.storage.add_docker_socket(mount_path="/some/path") + c1.storage._add_docker_socket(mount_path="/some/path") output = render.render() assert output["services"]["test_container"]["volumes"] == [ { diff --git a/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/validations.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_types.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volumes.py b/trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/storj/1.2.0/templates/library/base_v2_0_32/volumes.py rename to trains/stable/storj/1.2.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/storj/1.2.0/templates/macros/entrypoint.sh b/trains/stable/storj/1.2.1/templates/macros/entrypoint.sh similarity index 100% rename from trains/stable/storj/1.2.0/templates/macros/entrypoint.sh rename to trains/stable/storj/1.2.1/templates/macros/entrypoint.sh diff --git a/trains/stable/storj/1.2.0/templates/macros/init.sh b/trains/stable/storj/1.2.1/templates/macros/init.sh similarity index 100% rename from trains/stable/storj/1.2.0/templates/macros/init.sh rename to trains/stable/storj/1.2.1/templates/macros/init.sh diff --git a/trains/stable/storj/1.2.0/templates/test_values/basic-values.yaml b/trains/stable/storj/1.2.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/storj/1.2.0/templates/test_values/basic-values.yaml rename to trains/stable/storj/1.2.1/templates/test_values/basic-values.yaml diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/container.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/devices.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/environment.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/validations.py b/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/syncthing/1.1.0/README.md b/trains/stable/syncthing/1.1.1/README.md similarity index 100% rename from trains/stable/syncthing/1.1.0/README.md rename to trains/stable/syncthing/1.1.1/README.md diff --git a/trains/stable/syncthing/1.1.0/app.yaml b/trains/stable/syncthing/1.1.1/app.yaml similarity index 93% rename from trains/stable/syncthing/1.1.0/app.yaml rename to trains/stable/syncthing/1.1.1/app.yaml index 8abff7400a..c8d8a17e5b 100644 --- a/trains/stable/syncthing/1.1.0/app.yaml +++ b/trains/stable/syncthing/1.1.1/app.yaml @@ -26,8 +26,8 @@ keywords: - sync - file-sharing - backup -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -50,4 +50,4 @@ sources: - https://hub.docker.com/r/syncthing/syncthing title: Syncthing train: stable -version: 1.1.0 +version: 1.1.1 diff --git a/trains/stable/syncthing/1.1.0/ix_values.yaml b/trains/stable/syncthing/1.1.1/ix_values.yaml similarity index 100% rename from trains/stable/syncthing/1.1.0/ix_values.yaml rename to trains/stable/syncthing/1.1.1/ix_values.yaml diff --git a/trains/stable/syncthing/1.1.0/migrations/migrate_from_kubernetes b/trains/stable/syncthing/1.1.1/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migrate_from_kubernetes rename to trains/stable/syncthing/1.1.1/migrations/migrate_from_kubernetes diff --git a/trains/stable/syncthing/1.1.0/migrations/migration_helpers/__init__.py b/trains/stable/syncthing/1.1.1/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migration_helpers/__init__.py rename to trains/stable/syncthing/1.1.1/migrations/migration_helpers/__init__.py diff --git a/trains/stable/syncthing/1.1.0/migrations/migration_helpers/cpu.py b/trains/stable/syncthing/1.1.1/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migration_helpers/cpu.py rename to trains/stable/syncthing/1.1.1/migrations/migration_helpers/cpu.py diff --git a/trains/stable/syncthing/1.1.0/migrations/migration_helpers/dns_config.py b/trains/stable/syncthing/1.1.1/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migration_helpers/dns_config.py rename to trains/stable/syncthing/1.1.1/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/syncthing/1.1.0/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/syncthing/1.1.1/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/syncthing/1.1.1/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/syncthing/1.1.0/migrations/migration_helpers/memory.py b/trains/stable/syncthing/1.1.1/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migration_helpers/memory.py rename to trains/stable/syncthing/1.1.1/migrations/migration_helpers/memory.py diff --git a/trains/stable/syncthing/1.1.0/migrations/migration_helpers/resources.py b/trains/stable/syncthing/1.1.1/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migration_helpers/resources.py rename to trains/stable/syncthing/1.1.1/migrations/migration_helpers/resources.py diff --git a/trains/stable/syncthing/1.1.0/migrations/migration_helpers/storage.py b/trains/stable/syncthing/1.1.1/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/syncthing/1.1.0/migrations/migration_helpers/storage.py rename to trains/stable/syncthing/1.1.1/migrations/migration_helpers/storage.py diff --git a/trains/stable/syncthing/1.1.0/questions.yaml b/trains/stable/syncthing/1.1.1/questions.yaml similarity index 100% rename from trains/stable/syncthing/1.1.0/questions.yaml rename to trains/stable/syncthing/1.1.1/questions.yaml diff --git a/trains/stable/syncthing/1.1.0/templates/docker-compose.yaml b/trains/stable/syncthing/1.1.1/templates/docker-compose.yaml similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/docker-compose.yaml rename to trains/stable/syncthing/1.1.1/templates/docker-compose.yaml diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/__init__.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/__init__.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/configs.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/configs.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/container.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/depends.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/depends.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/deploy.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/deploy.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/device.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/device.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/devices.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/dns.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/dns.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/environment.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/error.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/error.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/formatter.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/formatter.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/functions.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/functions.py new file mode 100644 index 0000000000..7d082d8c46 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/functions.py @@ -0,0 +1,149 @@ +import re +import copy +import bcrypt +import secrets +from base64 import b64encode +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource +except ImportError: + from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource + + +class Functions: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def _bcrypt_hash(self, password): + hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + return hashed + + def _htpasswd(self, username, password): + hashed = self._bcrypt_hash(password) + return username + ":" + hashed + + def _secure_string(self, length): + return secrets.token_urlsafe(length) + + def _basic_auth(self, username, password): + return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") + + def _basic_auth_header(self, username, password): + return f"Basic {self._basic_auth(username, password)}" + + def _fail(self, message): + raise RenderError(message) + + def _camel_case(self, string): + return string.title() + + def _auto_cast(self, value): + try: + return int(value) + except ValueError: + pass + + try: + return float(value) + except ValueError: + pass + + if value.lower() in ["true", "false"]: + return value.lower() == "true" + + return value + + def _match_regex(self, value, regex): + if not re.match(regex, value): + return False + return True + + def _must_match_regex(self, value, regex): + if not self._match_regex(value, regex): + raise RenderError(f"Expected [{value}] to match [{regex}]") + return value + + def _is_boolean(self, string): + return string.lower() in ["true", "false"] + + def _is_number(self, string): + try: + float(string) + return True + except ValueError: + return False + + def _copy_dict(self, dict): + return copy.deepcopy(dict) + + def _merge_dicts(self, *dicts): + merged_dict = {} + for dictionary in dicts: + merged_dict.update(dictionary) + return merged_dict + + def _disallow_chars(self, string: str, chars: list[str], key: str): + for char in chars: + if char in string: + raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") + + def func_map(self): + # TODO: Check what is no longer used and remove + return { + "auto_cast": self._auto_cast, + "basic_auth_header": self._basic_auth_header, + "basic_auth": self._basic_auth, + "bcrypt_hash": self._bcrypt_hash, + "camel_case": self._camel_case, + "copy_dict": self._copy_dict, + "fail": self._fail, + "htpasswd": self._htpasswd, + "is_boolean": self._is_boolean, + "is_number": self._is_number, + "match_regex": self._match_regex, + "merge_dicts": self._merge_dicts, + "must_match_regex": self._must_match_regex, + "secure_string": self._secure_string, + "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, + } diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/labels.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/labels.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/notes.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/notes.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/portal.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/portal.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/portals.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/portals.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/ports.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/ports.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/render.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/render.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/resources.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/resources.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/restart.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/restart.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/storage.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/storage.py new file mode 100644 index 0000000000..e697ba902a --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/storage.py @@ -0,0 +1,116 @@ +from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .validations import valid_fs_path_or_raise + from .volume_mount import VolumeMount +except ImportError: + from error import RenderError + from validations import valid_fs_path_or_raise + from volume_mount import VolumeMount + + +class IxStorageTmpfsConfig(TypedDict): + size: NotRequired[int] + mode: NotRequired[str] + + +class AclConfig(TypedDict, total=False): + path: str + + +class IxStorageHostPathConfig(TypedDict): + path: NotRequired[str] # Either this or acl.path must be set + acl_enable: NotRequired[bool] + acl: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageIxVolumeConfig(TypedDict): + dataset_name: str + acl_enable: NotRequired[bool] + acl_entries: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageVolumeConfig(TypedDict): + volume_name: NotRequired[str] + nocopy: NotRequired[bool] + auto_permissions: NotRequired[bool] + + +class IxStorageNfsConfig(TypedDict): + server: str + path: str + options: NotRequired[list[str]] + + +class IxStorageCifsConfig(TypedDict): + server: str + path: str + username: str + password: str + domain: NotRequired[str] + options: NotRequired[list[str]] + + +IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] +IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] +IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] + + +class IxStorage(TypedDict): + type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] + read_only: NotRequired[bool] + + ix_volume_config: NotRequired[IxStorageIxVolumeConfig] + host_path_config: NotRequired[IxStorageHostPathConfig] + tmpfs_config: NotRequired[IxStorageTmpfsConfig] + volume_config: NotRequired[IxStorageVolumeConfig] + nfs_config: NotRequired[IxStorageNfsConfig] + cifs_config: NotRequired[IxStorageCifsConfig] + + +class Storage: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._volume_mounts: set[VolumeMount] = set() + + def add(self, mount_path: str, config: "IxStorage"): + mount_path = valid_fs_path_or_raise(mount_path) + if mount_path in [m.mount_path for m in self._volume_mounts]: + raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") + + volume_mount = VolumeMount(self._render_instance, mount_path, config) + self._volume_mounts.add(volume_mount) + + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def has_mounts(self) -> bool: + return bool(self._volume_mounts) + + def render(self): + return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/sysctls.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_functions.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_functions.py new file mode 100644 index 0000000000..0ea3b57d18 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_functions.py @@ -0,0 +1,88 @@ +import re +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + tests = [ + {"func": "auto_cast", "values": ["1"], "expected": 1}, + {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, + {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, + { + "func": "bcrypt_hash", + "values": ["my_pass"], + "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, + {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, + {"func": "fail", "values": ["my_message"], "expect_raise": True}, + { + "func": "htpasswd", + "values": ["my_user", "my_pass"], + "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "is_boolean", "values": ["true"], "expected": True}, + {"func": "is_boolean", "values": ["false"], "expected": True}, + {"func": "is_number", "values": ["1"], "expected": True}, + {"func": "is_number", "values": ["1.1"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, + {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, + {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, + {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, + {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, + ] + + for test in tests: + print(test["func"], test) + func = render.funcs[test["func"]] + if test.get("expect_raise", False): + with pytest.raises(Exception): + func(*test["values"]) + elif test.get("expect_regex"): + r = func(*test["values"]) + assert re.match(test["expect_regex"], r) is not None + else: + r = func(*test["values"]) + assert r == test["expected"] diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_sysctls.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_volumes.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_volumes.py new file mode 100644 index 0000000000..aef0d39481 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/tests/test_volumes.py @@ -0,0 +1,666 @@ +import pytest + + +from render import Render +from formatter import get_hashed_name_for_volume + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_volume_invalid_type(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "invalid_type"}) + + +def test_add_volume_empty_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("", {"type": "tmpfs"}) + + +def test_add_volume_duplicate_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_storage("/some/path", {"type": "tmpfs"}) + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "tmpfs"}) + + +def test_add_volume_host_path_invalid_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_host_path_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path"} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_with_acl_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_mount(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_acl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, + } + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test/acl", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "slave"}, + } + ] + + +def test_add_host_path_volume_mount_with_create_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_invalid_dataset_name(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_no_ix_volume_config(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume"} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_volume_mount(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_volume_mount_with_options(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = { + "type": "ix_volume", + "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, + } + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rslave"}, + } + ] + + +def test_cifs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_username(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_password(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_without_cifs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["verbose=true", "verbose=true"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["user=username"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": {"verbose": True}, + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": [{"verbose": True}], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_add_cifs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_cifs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["vers=3.0", "verbose=true"], + } + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "cifs", + "device": "//server/path", + "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_without_nfs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = { + "type": "nfs", + "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_add_nfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path"} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "nfs", + "device": ":/path", + "o": "addr=server,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_tmpfs_invalid_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_zero_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_invalid_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs"} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "tmpfs", + "target": "/some/path", + "read_only": False, + } + ] + + +def test_temporary_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "source": "test_temp_volume", + "type": "volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + + +def test_docker_volume_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume_missing_volume_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["volumes"] == {"test_volume": {}} + + +def test_anonymous_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} + ] + assert "volumes" not in output + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_not_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/some/path") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] diff --git a/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/validations.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_types.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volumes.py b/trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/library/base_v2_0_32/volumes.py rename to trains/stable/syncthing/1.1.1/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/syncthing/1.1.0/templates/test_values/basic-values.yaml b/trains/stable/syncthing/1.1.1/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/test_values/basic-values.yaml rename to trains/stable/syncthing/1.1.1/templates/test_values/basic-values.yaml diff --git a/trains/stable/syncthing/1.1.0/templates/test_values/host-values.yaml b/trains/stable/syncthing/1.1.1/templates/test_values/host-values.yaml similarity index 100% rename from trains/stable/syncthing/1.1.0/templates/test_values/host-values.yaml rename to trains/stable/syncthing/1.1.1/templates/test_values/host-values.yaml diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/container.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/container.py deleted file mode 100644 index a95e76734c..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/container.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .configs import ContainerConfigs - from .depends import Depends - from .deploy import Deploy - from .devices import Devices - from .dns import Dns - from .environment import Environment - from .error import RenderError - from .formatter import escape_dollar, get_image_with_hashed_data - from .healthcheck import Healthcheck - from .labels import Labels - from .ports import Ports - from .restart import RestartPolicy - from .validations import valid_network_mode_or_raise, valid_cap_or_raise - from .storage import Storage - from .sysctls import Sysctls -except ImportError: - from configs import ContainerConfigs - from depends import Depends - from deploy import Deploy - from devices import Devices - from dns import Dns - from environment import Environment - from error import RenderError - from formatter import escape_dollar, get_image_with_hashed_data - from healthcheck import Healthcheck - from labels import Labels - from ports import Ports - from restart import RestartPolicy - from validations import valid_network_mode_or_raise, valid_cap_or_raise - from storage import Storage - from sysctls import Sysctls - - -class Container: - def __init__(self, render_instance: "Render", name: str, image: str): - self._render_instance = render_instance - - self._name: str = name - self._image: str = self._resolve_image(image) - self._build_image: str = "" - self._user: str = "" - self._tty: bool = False - self._stdin_open: bool = False - self._init: bool | None = None - self._read_only: bool | None = None - self._hostname: str = "" - self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly - self._cap_add: set[str] = set() - self._security_opt: set[str] = set(["no-new-privileges"]) - self._group_add: set[int | str] = set() - self._network_mode: str = "" - self._entrypoint: list[str] = [] - self._command: list[str] = [] - self._grace_period: int | None = None - self._shm_size: int | None = None - self._storage: Storage = Storage(self._render_instance) - self.sysctls: Sysctls = Sysctls(self._render_instance, self) - self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) - self.deploy: Deploy = Deploy(self._render_instance) - self.networks: set[str] = set() - self.devices: Devices = Devices(self._render_instance) - self.environment: Environment = Environment(self._render_instance, self.deploy.resources) - self.dns: Dns = Dns(self._render_instance) - self.depends: Depends = Depends(self._render_instance) - self.healthcheck: Healthcheck = Healthcheck(self._render_instance) - self.labels: Labels = Labels(self._render_instance) - self.restart: RestartPolicy = RestartPolicy(self._render_instance) - self.ports: Ports = Ports(self._render_instance) - - self._auto_set_network_mode() - self._auto_add_labels() - self._auto_add_groups() - - def _auto_add_groups(self): - self.add_group(568) - - def _auto_set_network_mode(self): - if self._render_instance.values.get("network", {}).get("host_network", False): - self.set_network_mode("host") - - def _auto_add_labels(self): - labels = self._render_instance.values.get("labels", []) - if not labels: - return - - for label in labels: - containers = label.get("containers", []) - if not containers: - raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') - - if self._name in containers: - self.labels.add_label(label["key"], label["value"]) - - def _resolve_image(self, image: str): - images = self._render_instance.values["images"] - if image not in images: - raise RenderError( - f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" - ) - repo = images[image].get("repository", "") - tag = images[image].get("tag", "") - - if not repo: - raise RenderError(f"Repository not found for image [{image}]") - if not tag: - raise RenderError(f"Tag not found for image [{image}]") - - return f"{repo}:{tag}" - - def build_image(self, content: list[str | None]): - dockerfile = f"FROM {self._image}\n" - for line in content: - if not line: - continue - if line.startswith("FROM"): - # TODO: This will also block multi-stage builds - # We can revisit this later if we need it - raise RenderError( - "FROM cannot be used in build image. Define the base image when creating the container." - ) - dockerfile += line + "\n" - - self._build_image = dockerfile - self._image = get_image_with_hashed_data(self._image, dockerfile) - - def set_user(self, user: int, group: int): - for i in (user, group): - if not isinstance(i, int) or i < 0: - raise RenderError(f"User/Group [{i}] is not valid") - self._user = f"{user}:{group}" - - def add_group(self, group: int | str): - if isinstance(group, str): - group = str(group).strip() - if group.isdigit(): - raise RenderError(f"Group is a number [{group}] but passed as a string") - - if group in self._group_add: - raise RenderError(f"Group [{group}] already added") - self._group_add.add(group) - - def get_current_groups(self) -> list[str]: - return [str(g) for g in self._group_add] - - def set_tty(self, enabled: bool = False): - self._tty = enabled - - def set_stdin(self, enabled: bool = False): - self._stdin_open = enabled - - def set_init(self, enabled: bool = False): - self._init = enabled - - def set_read_only(self, enabled: bool = False): - self._read_only = enabled - - def set_hostname(self, hostname: str): - self._hostname = hostname - - def set_grace_period(self, grace_period: int): - if grace_period < 0: - raise RenderError(f"Grace period [{grace_period}] cannot be negative") - self._grace_period = grace_period - - def add_caps(self, caps: list[str]): - for c in caps: - if c in self._cap_add: - raise RenderError(f"Capability [{c}] already added") - self._cap_add.add(valid_cap_or_raise(c)) - - def add_security_opt(self, opt: str): - if opt in self._security_opt: - raise RenderError(f"Security Option [{opt}] already added") - self._security_opt.add(opt) - - def remove_security_opt(self, opt: str): - self._security_opt.remove(opt) - - def set_network_mode(self, mode: str): - self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) - - def set_entrypoint(self, entrypoint: list[str]): - self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] - - def set_command(self, command: list[str]): - self._command = [escape_dollar(str(e)) for e in command] - - def add_storage(self, mount_path: str, config: "IxStorage"): - self._storage.add(mount_path, config) - - def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): - self.add_group(999) - self._storage._add_docker_socket(read_only, mount_path) - - def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): - self._storage._add_tun_device(read_only, mount_path) - - def add_snd_device(self): - self.add_group(29) - self.devices._add_snd_device() - - def set_shm_size_mb(self, size: int): - self._shm_size = size - - # Easily remove devices from the container - # Useful in dependencies like postgres and redis - # where there is no need to pass devices to them - def remove_devices(self): - self.deploy.resources.remove_devices() - self.devices.remove_devices() - - @property - def storage(self): - return self._storage - - def render(self) -> dict[str, Any]: - if self._network_mode and self.networks: - raise RenderError("Cannot set both [network_mode] and [networks]") - - result = { - "image": self._image, - "platform": "linux/amd64", - "tty": self._tty, - "stdin_open": self._stdin_open, - "restart": self.restart.render(), - "cap_drop": sorted(self._cap_drop), - "healthcheck": self.healthcheck.render(), - } - - if self._hostname: - result["hostname"] = self._hostname - - if self._build_image: - result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} - - if self.configs.has_configs(): - result["configs"] = self.configs.render() - - if self._init is not None: - result["init"] = self._init - - if self._read_only is not None: - result["read_only"] = self._read_only - - if self._grace_period is not None: - result["stop_grace_period"] = f"{self._grace_period}s" - - if self._user: - result["user"] = self._user - - if self.deploy.resources.has_gpus() or self.devices.has_gpus(): - self.add_group(44) # video - self.add_group(107) # render - - if self._group_add: - result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) - - if self._shm_size is not None: - result["shm_size"] = f"{self._shm_size}M" - - if self._cap_add: - result["cap_add"] = sorted(self._cap_add) - - if self._security_opt: - result["security_opt"] = sorted(self._security_opt) - - if self._network_mode: - result["network_mode"] = self._network_mode - - if self.sysctls.has_sysctls(): - result["sysctls"] = self.sysctls.render() - - if self._network_mode != "host": - if self.ports.has_ports(): - result["ports"] = self.ports.render() - - if self._entrypoint: - result["entrypoint"] = self._entrypoint - - if self._command: - result["command"] = self._command - - if self.devices.has_devices(): - result["devices"] = self.devices.render() - - if self.deploy.has_deploy(): - result["deploy"] = self.deploy.render() - - if self.environment.has_variables(): - result["environment"] = self.environment.render() - - if self.labels.has_labels(): - result["labels"] = self.labels.render() - - if self.dns.has_dns_nameservers(): - result["dns"] = self.dns.render_dns_nameservers() - - if self.dns.has_dns_searches(): - result["dns_search"] = self.dns.render_dns_searches() - - if self.dns.has_dns_opts(): - result["dns_opt"] = self.dns.render_dns_opts() - - if self.depends.has_dependencies(): - result["depends_on"] = self.depends.render() - - if self._storage.has_mounts(): - result["volumes"] = self._storage.render() - - return result diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/deps.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/deps.py deleted file mode 100644 index b3607fa6ab..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/deps.py +++ /dev/null @@ -1,454 +0,0 @@ -import os -import json -import urllib.parse -from typing import TYPE_CHECKING, TypedDict, NotRequired - -if TYPE_CHECKING: - from render import Render - from storage import IxStorage - -try: - from .error import RenderError - from .validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) -except ImportError: - from error import RenderError - from validations import ( - valid_port_or_raise, - valid_fs_path_or_raise, - valid_octal_mode_or_raise, - valid_redis_password_or_raise, - ) - - -class PostgresConfig(TypedDict): - user: str - password: str - database: str - port: NotRequired[int] - volume: "IxStorage" - - -class MariadbConfig(TypedDict): - user: str - password: str - database: str - root_password: NotRequired[str] - port: NotRequired[int] - auto_upgrade: NotRequired[bool] - volume: "IxStorage" - - -class RedisConfig(TypedDict): - password: str - port: NotRequired[int] - volume: "IxStorage" - - -class PermsContainer: - def __init__(self, render_instance: "Render", name: str): - self._render_instance = render_instance - self._name = name - self.actions: set[str] = set() - self.parsed_configs: list[dict] = [] - - def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - identifier = self.normalize_identifier_for_path(identifier) - if identifier in self.actions: - raise RenderError(f"Action with id [{identifier}] already used for another permission action") - - parsed_action = self.parse_action(identifier, volume_config, action_config) - if parsed_action: - self.parsed_configs.append(parsed_action) - self.actions.add(identifier) - - def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): - valid_modes = [ - "always", # Always set permissions, without checking. - "check", # Checks if permissions are correct, and set them if not. - ] - mode = action_config.get("mode", "check") - uid = action_config.get("uid", None) - gid = action_config.get("gid", None) - chmod = action_config.get("chmod", None) - recursive = action_config.get("recursive", False) - mount_path = os.path.join("/mnt/permission", identifier) - is_temporary = False - - vol_type = volume_config.get("type", "") - match vol_type: - case "temporary": - # If it is a temporary volume, we force auto permissions - # and set is_temporary to True, so it will be cleaned up - is_temporary = True - recursive = True - case "volume": - if not volume_config.get("volume_config", {}).get("auto_permissions", False): - return None - case "host_path": - host_path_config = volume_config.get("host_path_config", {}) - # Skip when ACL enabled - if host_path_config.get("acl_enable", False): - return None - if not host_path_config.get("auto_permissions", False): - return None - case "ix_volume": - ix_vol_config = volume_config.get("ix_volume_config", {}) - # Skip when ACL enabled - if ix_vol_config.get("acl_enable", False): - return None - # For ix_volumes, we default to auto_permissions = True - if not ix_vol_config.get("auto_permissions", True): - return None - case _: - # Skip for other types - return None - - if mode not in valid_modes: - raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") - if not isinstance(uid, int) or not isinstance(gid, int): - raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") - if chmod is not None: - chmod = valid_octal_mode_or_raise(chmod) - - mount_path = valid_fs_path_or_raise(mount_path) - return { - "mount_path": mount_path, - "volume_config": volume_config, - "action_data": { - "mount_path": mount_path, - "is_temporary": is_temporary, - "identifier": identifier, - "recursive": recursive, - "mode": mode, - "uid": uid, - "gid": gid, - "chmod": chmod, - }, - } - - def normalize_identifier_for_path(self, identifier: str): - return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") - - def has_actions(self): - return bool(self.actions) - - def activate(self): - if len(self.parsed_configs) != len(self.actions): - raise RenderError("Number of actions and parsed configs does not match") - - if not self.has_actions(): - raise RenderError("No actions added. Check if there are actions before activating") - - # Add the container and set it up - c = self._render_instance.add_container(self._name, "python_permissions_image") - c.set_user(0, 0) - c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) - c.set_network_mode("none") - - # Don't attach any devices - c.remove_devices() - - c.deploy.resources.set_profile("medium") - c.restart.set_policy("on-failure", maximum_retry_count=1) - c.healthcheck.disable() - - c.set_entrypoint(["python3", "/script/run.py"]) - script = "#!/usr/bin/env python3\n" - script += get_script() - c.configs.add("permissions_run_script", script, "/script/run.py", "0700") - - actions_data: list[dict] = [] - for parsed in self.parsed_configs: - c.add_storage(parsed["mount_path"], parsed["volume_config"]) - actions_data.append(parsed["action_data"]) - - actions_data_json = json.dumps(actions_data) - c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") - - -def get_script(): - return """ -import os -import json -import time -import shutil - -with open("/script/actions.json", "r") as f: - actions_data = json.load(f) - -if not actions_data: - # If this script is called, there should be actions data - raise ValueError("No actions data found") - -def fix_perms(path, chmod, recursive=False): - print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") - os.chmod(path, int(chmod, 8)) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chmod(os.path.join(root, f), int(chmod, 8)) - print("Permissions after changes:") - print_chmod_stat() - -def fix_owner(path, uid, gid, recursive=False): - print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") - os.chown(path, uid, gid) - if recursive: - for root, dirs, files in os.walk(path): - for f in files: - os.chown(os.path.join(root, f), uid, gid) - print("Ownership after changes:") - print_chown_stat() - -def print_chown_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") - -def print_chmod_stat(): - curr_stat = os.stat(action["mount_path"]) - print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") - -def print_chown_diff(curr_stat, uid, gid): - print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") - -def print_chmod_diff(curr_stat, mode): - print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") - -def perform_action(action): - start_time = time.time() - print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") - - if not os.path.isdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not a directory, skipping...") - return - - if action["is_temporary"]: - print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") - for item in os.listdir(action["mount_path"]): - item_path = os.path.join(action["mount_path"], item) - - # Exclude the safe directory, where we can use to mount files temporarily - if os.path.basename(item_path) == "ix-safe": - continue - if os.path.isdir(item_path): - shutil.rmtree(item_path) - else: - os.remove(item_path) - - if not action["is_temporary"] and os.listdir(action["mount_path"]): - print(f"Path [{action['mount_path']}] is not empty, skipping...") - return - - print(f"Current Ownership and Permissions on [{action['mount_path']}]:") - curr_stat = os.stat(action["mount_path"]) - print_chown_diff(curr_stat, action["uid"], action["gid"]) - print_chmod_diff(curr_stat, action["chmod"]) - print("---") - - if action["mode"] == "always": - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - return - - elif action["mode"] == "check": - if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: - print("Ownership is incorrect. Fixing...") - fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) - else: - print("Ownership is correct. Skipping...") - - if not action["chmod"]: - print("Skipping permissions check, chmod is falsy") - else: - if oct(curr_stat.st_mode)[3:] != action["chmod"]: - print("Permissions are incorrect. Fixing...") - fix_perms(action["mount_path"], action["chmod"], action["recursive"]) - else: - print("Permissions are correct. Skipping...") - - print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") - print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") - print() - -if __name__ == "__main__": - start_time = time.time() - for action in actions_data: - perform_action(action) - print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") -""" - - -class Deps: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - - def perms(self, name: str): - return PermsContainer(self._render_instance, name) - - def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): - return PostgresContainer(self._render_instance, name, image, config, perms_instance) - - def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): - return RedisContainer(self._render_instance, name, image, config, perms_instance) - - def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): - return MariadbContainer(self._render_instance, name, image, config, perms_instance) - - -class PostgresContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for postgres") - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("postgres") - c.remove_devices() - - c.add_storage("/var/lib/postgresql/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("POSTGRES_USER", config["user"]) - c.environment.add_env("POSTGRES_PASSWORD", config["password"]) - c.environment.add_env("POSTGRES_DB", config["database"]) - c.environment.add_env("POSTGRES_PORT", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container - - def _get_port(self): - return self._config.get("port") or 5432 - - def get_url(self, variant: str): - user = urllib.parse.quote_plus(self._config["user"]) - password = urllib.parse.quote_plus(self._config["password"]) - creds = f"{user}:{password}" - addr = f"{self._name}:{self._get_port()}" - db = self._config["database"] - - match variant: - case "postgres": - return f"postgres://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql": - return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" - case "postgresql_no_creds": - return f"postgresql://{addr}/{db}?sslmode=disable" - case "host_port": - return addr - case _: - raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") - - -class RedisContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - self._config = config - - for key in ("password", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for redis") - - valid_redis_password_or_raise(config["password"]) - - port = valid_port_or_raise(self._get_port()) - - c = self._render_instance.add_container(name, image) - c.set_user(1001, 0) - c.healthcheck.set_test("redis") - c.remove_devices() - - c.add_storage("/bitnami/redis/data", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} - ) - - c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") - c.environment.add_env("REDIS_PASSWORD", config["password"]) - c.environment.add_env("REDIS_PORT_NUMBER", port) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - def _get_port(self): - return self._config.get("port") or 6379 - - def get_url(self, variant: str): - addr = f"{self._name}:{self._get_port()}" - password = urllib.parse.quote_plus(self._config["password"]) - - match variant: - case "redis": - return f"redis://default:{password}@{addr}" - - @property - def container(self): - return self._container - - -class MariadbContainer: - def __init__( - self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer - ): - self._render_instance = render_instance - self._name = name - - for key in ("user", "password", "database", "volume"): - if key not in config: - raise RenderError(f"Expected [{key}] to be set for mariadb") - - port = valid_port_or_raise(config.get("port") or 3306) - root_password = config.get("root_password") or config["password"] - auto_upgrade = config.get("auto_upgrade", True) - - c = self._render_instance.add_container(name, image) - c.set_user(999, 999) - c.healthcheck.set_test("mariadb") - c.remove_devices() - - c.add_storage("/var/lib/mysql", config["volume"]) - perms_instance.add_or_skip_action( - f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} - ) - - c.environment.add_env("MARIADB_USER", config["user"]) - c.environment.add_env("MARIADB_PASSWORD", config["password"]) - c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) - c.environment.add_env("MARIADB_DATABASE", config["database"]) - c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) - c.set_command(["--port", str(port)]) - - # Store container for further configuration - # For example: c.depends.add_dependency("other_container", "service_started") - self._container = c - - @property - def container(self): - return self._container diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/devices.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/devices.py deleted file mode 100644 index ae22c79d2e..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/devices.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .device import Device -except ImportError: - from error import RenderError - from device import Device - - -class Devices: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._devices: set[Device] = set() - - # Tracks all container device paths to make sure they are not duplicated - self._container_device_paths: set[str] = set() - # Scan values for devices we should automatically add - # for example /dev/dri for gpus - self._auto_add_devices_from_values() - - def _auto_add_devices_from_values(self): - resources = self._render_instance.values.get("resources", {}) - - if resources.get("gpus", {}).get("use_all_gpus", False): - self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) - - def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): - # Host device can be mapped to multiple container devices, - # so we only make sure container devices are not duplicated - if container_device in self._container_device_paths: - raise RenderError(f"Device with container path [{container_device}] already added") - - self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) - self._container_device_paths.add(container_device) - - def add_usb_bus(self): - self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) - - def _add_snd_device(self): - self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) - - def has_devices(self): - return len(self._devices) > 0 - - # Mainly will be used from dependencies - # There is no reason to pass devices to - # redis or postgres for example - def remove_devices(self): - self._devices.clear() - self._container_device_paths.clear() - - # Check if there are any gpu devices - # Used to determine if we should add groups - # like 'video' to the container - def has_gpus(self): - for d in self._devices: - if d.host_device == "/dev/dri": - return True - return False - - def render(self) -> list[str]: - return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/environment.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/environment.py deleted file mode 100644 index 850a3afd8e..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/environment.py +++ /dev/null @@ -1,109 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render -try: - from .error import RenderError - from .formatter import escape_dollar - from .resources import Resources -except ImportError: - from error import RenderError - from formatter import escape_dollar - from resources import Resources - - -class Environment: - def __init__(self, render_instance: "Render", resources: Resources): - self._render_instance = render_instance - self._resources = resources - # Stores variables that user defined - self._user_vars: dict[str, Any] = {} - # Stores variables that are automatically added (based on values) - self._auto_variables: dict[str, Any] = {} - # Stores variables that are added by the application developer - self._app_dev_variables: dict[str, Any] = {} - - self._auto_add_variables_from_values() - - def _auto_add_variables_from_values(self): - self._add_generic_variables() - self._add_nvidia_variables() - - def _add_generic_variables(self): - self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") - self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") - self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") - - run_as = self._render_instance.values.get("run_as", {}) - user = run_as.get("user") - group = run_as.get("group") - if user: - self._auto_variables["PUID"] = user - self._auto_variables["UID"] = user - self._auto_variables["USER_ID"] = user - if group: - self._auto_variables["PGID"] = group - self._auto_variables["GID"] = group - self._auto_variables["GROUP_ID"] = group - - def _add_nvidia_variables(self): - if self._resources._nvidia_ids: - self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) - else: - self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" - - def _format_value(self, v: Any) -> str: - value = str(v) - - # str(bool) returns "True" or "False", - # but we want "true" or "false" - if isinstance(v, bool): - value = value.lower() - return value - - def add_env(self, name: str, value: Any): - if not name: - raise RenderError(f"Environment variable name cannot be empty. [{name}]") - if name in self._app_dev_variables.keys(): - raise RenderError( - f"Found duplicate environment variable [{name}] in application developer environment variables." - ) - self._app_dev_variables[name] = value - - def add_user_envs(self, user_env: list[dict]): - for item in user_env: - if not item.get("name"): - raise RenderError(f"Environment variable name cannot be empty. [{item}]") - if item["name"] in self._user_vars.keys(): - raise RenderError( - f"Found duplicate environment variable [{item['name']}] in user environment variables." - ) - self._user_vars[item["name"]] = item.get("value") - - def has_variables(self): - return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 - - def render(self): - result: dict[str, str] = {} - - # Add envs from auto variables - result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) - - # Track defined keys for faster lookup - defined_keys = set(result.keys()) - - # Add envs from application developer (prohibit overwriting auto variables) - for k, v in self._app_dev_variables.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") - result[k] = self._format_value(v) - defined_keys.add(k) - - # Add envs from user (prohibit overwriting app developer envs and auto variables) - for k, v in self._user_vars.items(): - if k in defined_keys: - raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") - result[k] = self._format_value(v) - - return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/healthcheck.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/healthcheck.py deleted file mode 100644 index 36ae5d90aa..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/healthcheck.py +++ /dev/null @@ -1,193 +0,0 @@ -from typing import Any, TYPE_CHECKING - -if TYPE_CHECKING: - from render import Render - -try: - from .error import RenderError - from .formatter import escape_dollar - from .validations import valid_http_path_or_raise -except ImportError: - from error import RenderError - from formatter import escape_dollar - from validations import valid_http_path_or_raise - - -class Healthcheck: - def __init__(self, render_instance: "Render"): - self._render_instance = render_instance - self._test: str | list[str] = "" - self._interval_sec: int = 10 - self._timeout_sec: int = 5 - self._retries: int = 30 - self._start_period_sec: int = 10 - self._disabled: bool = False - - def _get_test(self): - if isinstance(self._test, str): - return escape_dollar(self._test) - - return [escape_dollar(t) for t in self._test] - - def disable(self): - self._disabled = True - - def set_custom_test(self, test: str | list[str]): - if self._disabled: - raise RenderError("Cannot set custom test when healthcheck is disabled") - self._test = test - - def set_test(self, variant: str, config: dict | None = None): - config = config or {} - self.set_custom_test(test_mapping(variant, config)) - - def set_interval(self, interval: int): - self._interval_sec = interval - - def set_timeout(self, timeout: int): - self._timeout_sec = timeout - - def set_retries(self, retries: int): - self._retries = retries - - def set_start_period(self, start_period: int): - self._start_period_sec = start_period - - def render(self): - if self._disabled: - return {"disable": True} - - if not self._test: - raise RenderError("Healthcheck test is not set") - - return { - "test": self._get_test(), - "interval": f"{self._interval_sec}s", - "timeout": f"{self._timeout_sec}s", - "retries": self._retries, - "start_period": f"{self._start_period_sec}s", - } - - -def test_mapping(variant: str, config: dict | None = None) -> str: - config = config or {} - tests = { - "curl": curl_test, - "wget": wget_test, - "http": http_test, - "netcat": netcat_test, - "tcp": tcp_test, - "redis": redis_test, - "postgres": postgres_test, - "mariadb": mariadb_test, - } - - if variant not in tests: - raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") - - return tests[variant](config) - - -def get_key(config: dict, key: str, default: Any, required: bool): - if not config.get(key): - if not required: - return default - raise RenderError(f"Expected [{key}] to be set") - return config[key] - - -def curl_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--insecure") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for curl test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "curl --silent --output /dev/null --show-error --fail" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def wget_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - scheme = get_key(config, "scheme", "http", False) - host = get_key(config, "host", "127.0.0.1", False) - headers = get_key(config, "headers", [], False) - - opts = [] - if scheme == "https": - opts.append("--no-check-certificate") - - for header in headers: - if not header[0] or not header[1]: - raise RenderError("Expected [header] to be a list of two items for wget test") - opts.append(f'--header "{header[0]}: {header[1]}"') - - cmd = "wget --spider --quiet" - if opts: - cmd += f" {' '.join(opts)}" - cmd += f" {scheme}://{host}:{port}{path}" - return cmd - - -def http_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - path = valid_http_path_or_raise(get_key(config, "path", "/", False)) - host = get_key(config, "host", "127.0.0.1", False) - - return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa - - -def netcat_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"nc -z -w 1 {host} {port}" - - -def tcp_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", None, True) - host = get_key(config, "host", "127.0.0.1", False) - - return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" - - -def redis_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 6379, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" - - -def postgres_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 5432, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" - - -def mariadb_test(config: dict) -> str: - config = config or {} - port = get_key(config, "port", 3306, False) - host = get_key(config, "host", "127.0.0.1", False) - - return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_container.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_container.py deleted file mode 100644 index 61a22a5df2..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_container.py +++ /dev/null @@ -1,324 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_empty_container_name(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container(" ", "test_image") - - -def test_resolve_image(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["image"] == "nginx:latest" - - -def test_missing_repo(mock_values): - mock_values["images"]["test_image"]["repository"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_missing_tag(mock_values): - mock_values["images"]["test_image"]["tag"] = "" - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "test_image") - - -def test_non_existing_image(mock_values): - render = Render(mock_values) - with pytest.raises(Exception): - render.add_container("test_container", "non_existing_image") - - -def test_tty(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_tty(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["tty"] is True - - -def test_init(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_init(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["init"] is True - - -def test_read_only(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_read_only(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["read_only"] is True - - -def test_stdin(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_stdin(True) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stdin_open"] is True - - -def test_hostname(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_hostname("test_hostname") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["hostname"] == "test_hostname" - - -def test_grace_period(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_grace_period(10) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["stop_grace_period"] == "10s" - - -def test_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_user(1000, 1000) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["user"] == "1000:1000" - - -def test_invalid_user(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_user(-100, 1000) - - -def test_add_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - c1.add_group("video") - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] - - -def test_add_duplicate_group(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_group(1000) - with pytest.raises(Exception): - c1.add_group(1000) - - -def test_add_group_as_string(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_group("1000") - - -def test_add_docker_socket(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_docker_socket() - output = render.render() - assert output["services"]["test_container"]["group_add"] == [568, 999] - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/var/run/docker.sock", - "target": "/var/run/docker.sock", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_tun_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_tun_device() - output = render.render() - assert output["services"]["test_container"]["volumes"] == [ - { - "type": "bind", - "source": "/dev/net/tun", - "target": "/dev/net/tun", - "read_only": True, - "bind": { - "propagation": "rprivate", - "create_host_path": False, - }, - } - ] - - -def test_snd_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_snd_device() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] - assert output["services"]["test_container"]["group_add"] == [29, 568] - - -def test_shm_size(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_shm_size_mb(10) - output = render.render() - assert output["services"]["test_container"]["shm_size"] == "10M" - - -def test_valid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_caps(["ALL", "NET_ADMIN"]) - output = render.render() - assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] - assert output["services"]["test_container"]["cap_drop"] == ["ALL"] - - -def test_add_duplicate_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) - - -def test_invalid_caps(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_caps(["invalid_cap"]) - - -def test_remove_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.remove_security_opt("no-new-privileges") - output = render.render() - assert "security_opt" not in output["services"]["test_container"] - - -def test_add_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.add_security_opt("seccomp=unconfined") - output = render.render() - assert output["services"]["test_container"]["security_opt"] == [ - "no-new-privileges", - "seccomp=unconfined", - ] - - -def test_add_duplicate_security_opt(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.add_security_opt("no-new-privileges") - - -def test_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("host") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_auto_network_mode_with_host_network(mock_values): - mock_values["network"] = {"host_network": True} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "host" - - -def test_network_mode_with_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.set_network_mode("service:test_container") - output = render.render() - assert output["services"]["test_container"]["network_mode"] == "service:test_container" - - -def test_network_mode_with_container_missing(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("service:missing_container") - - -def test_invalid_network_mode(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.set_network_mode("invalid_mode") - - -def test_entrypoint(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] - - -def test_command(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.set_command(["echo", "hello $MY_ENV"]) - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_deps.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_deps.py deleted file mode 100644 index f9562ba4f2..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_deps.py +++ /dev/null @@ -1,380 +0,0 @@ -import json -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_postgres_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.postgres( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_postgres(mock_values): - mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - p = render.deps.postgres( - "pg_container", - "pg_image", - { - "user": "test_user", - "password": "test_@password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - p.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert ( - p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" - ) - assert "devices" not in output["services"]["pg_container"] - assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] - assert output["services"]["pg_container"]["image"] == "postgres:latest" - assert output["services"]["pg_container"]["user"] == "999:999" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["pg_container"]["healthcheck"] == { - "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["pg_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/postgresql/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["pg_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "POSTGRES_USER": "test_user", - "POSTGRES_PASSWORD": "test_@password", - "POSTGRES_DB": "test_database", - "POSTGRES_PORT": "5432", - } - assert output["services"]["pg_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - assert output["services"]["perms_container"]["restart"] == "on-failure:1" - - -def test_add_redis_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test_password", "volume": {}}, # type: ignore - ) - - -def test_add_redis_with_password_with_spaces(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.redis( - "test_container", - "test_image", - {"password": "test password", "volume": {}}, # type: ignore - ) - - -def test_add_redis(mock_values): - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - r = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test&password@", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - c1.environment.add_env("REDIS_URL", r.get_url("redis")) - if perms_container.has_actions(): - perms_container.activate() - r.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["redis_container"] - assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] - assert ( - output["services"]["test_container"]["environment"]["REDIS_URL"] - == "redis://default:test%26password%40@redis_container:6379" - ) - assert output["services"]["redis_container"]["image"] == "redis:latest" - assert output["services"]["redis_container"]["user"] == "1001:0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["redis_container"]["healthcheck"] == { - "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["redis_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/bitnami/redis/data", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["redis_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "ALLOW_EMPTY_PASSWORD": "no", - "REDIS_PASSWORD": "test&password@", - "REDIS_PORT_NUMBER": "6379", - } - assert output["services"]["redis_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_mariadb_missing_config(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - render.deps.mariadb( - "test_container", - "test_image", - {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore - ) - - -def test_add_mariadb(mock_values): - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - perms_container = render.deps.perms("perms_container") - m = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - if perms_container.has_actions(): - perms_container.activate() - m.container.depends.add_dependency("perms_container", "service_completed_successfully") - output = render.render() - assert "devices" not in output["services"]["mariadb_container"] - assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] - assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" - assert output["services"]["mariadb_container"]["user"] == "999:999" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" - assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" - assert output["services"]["mariadb_container"]["healthcheck"] == { - "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - assert output["services"]["mariadb_container"]["volumes"] == [ - { - "type": "volume", - "source": "test_volume", - "target": "/var/lib/mysql", - "read_only": False, - "volume": {"nocopy": False}, - } - ] - assert output["services"]["mariadb_container"]["environment"] == { - "TZ": "Etc/UTC", - "UMASK": "002", - "UMASK_SET": "002", - "NVIDIA_VISIBLE_DEVICES": "void", - "MARIADB_USER": "test_user", - "MARIADB_PASSWORD": "test_password", - "MARIADB_ROOT_PASSWORD": "test_password", - "MARIADB_DATABASE": "test_database", - "MARIADB_AUTO_UPGRADE": "true", - } - assert output["services"]["mariadb_container"]["depends_on"] == { - "perms_container": {"condition": "service_completed_successfully"} - } - - -def test_add_perms_container(mock_values): - mock_values["ix_volumes"] = { - "test_dataset1": "/mnt/test/1", - "test_dataset2": "/mnt/test/2", - "test_dataset3": "/mnt/test/3", - } - mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "latest"} - mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} - mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - - # fmt: off - volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} - host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} - host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} - host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa - ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} - ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa - ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa - temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} - # fmt: on - - c1.add_storage("/some/path1", volume_perms) - c1.add_storage("/some/path2", volume_no_perms) - c1.add_storage("/some/path3", host_path_perms) - c1.add_storage("/some/path4", host_path_no_perms) - c1.add_storage("/some/path5", host_path_acl_perms) - c1.add_storage("/some/path6", ix_volume_no_perms) - c1.add_storage("/some/path7", ix_volume_perms) - c1.add_storage("/some/path8", ix_volume_acl_perms) - c1.add_storage("/some/path9", temp_volume) - - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) - perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) - - postgres = render.deps.postgres( - "postgres_container", - "postgres_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - redis = render.deps.redis( - "redis_container", - "redis_image", - { - "password": "test_password", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - mariadb = render.deps.mariadb( - "mariadb_container", - "mariadb_image", - { - "user": "test_user", - "password": "test_password", - "database": "test_database", - "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, - }, - perms_container, - ) - - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert output["services"]["test_perms_container"]["network_mode"] == "none" - assert output["services"]["test_container"]["depends_on"] == { - "test_perms_container": {"condition": "service_completed_successfully"} - } - assert output["configs"]["permissions_run_script"]["content"] != "" - # fmt: off - content = [ - {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa - {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa - ] - # fmt: on - assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) - - -def test_add_duplicate_perms_action(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - with pytest.raises(Exception): - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - - -def test_add_perm_action_without_auto_perms_enabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} - c1.add_storage("/some/path", vol_config) - perms_container = render.deps.perms("test_perms_container") - perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) - if perms_container.has_actions(): - perms_container.activate() - c1.depends.add_dependency("test_perms_container", "service_completed_successfully") - output = render.render() - assert "configs" not in output - assert "ix-test_perms_container" not in output["services"] - assert "depends_on" not in output["services"]["test_container"] diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_device.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_device.py deleted file mode 100644 index 7455c829f6..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_device.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_add_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] - - -def test_devices_without_host(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("", "/c/dev/sda") - - -def test_devices_without_container(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "") - - -def test_add_duplicate_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda") - - -def test_add_device_with_invalid_container_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "c/dev/sda") - - -def test_add_device_with_invalid_host_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("h/dev/sda", "/c/dev/sda") - - -def test_add_disallowed_device(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/dri", "/c/dev/sda") - - -def test_add_device_with_invalid_cgroup_perm(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") - - -def test_automatically_add_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] - assert output["services"]["test_container"]["group_add"] == [44, 107, 568] - - -def test_remove_gpu_devices(mock_values): - mock_values["resources"] = {"gpus": {"use_all_gpus": True}} - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.remove_devices() - output = render.render() - assert "devices" not in output["services"]["test_container"] - assert output["services"]["test_container"]["group_add"] == [568] - - -def test_add_usb_bus(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.devices.add_usb_bus() - output = render.render() - assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] - - -def test_add_usb_bus_disallowed(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_environment.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_environment.py deleted file mode 100644 index 209f67551b..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_environment.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest - - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_auto_add_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - mock_values["run_as"] = {"user": "1000", "group": "1000"} - mock_values["resources"] = { - "gpus": { - "nvidia_gpu_selection": { - "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, - "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, - }, - } - } - - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert len(envs) == 11 - assert envs["TZ"] == "Etc/UTC" - assert envs["PUID"] == "1000" - assert envs["UID"] == "1000" - assert envs["USER_ID"] == "1000" - assert envs["PGID"] == "1000" - assert envs["GID"] == "1000" - assert envs["GROUP_ID"] == "1000" - assert envs["UMASK"] == "002" - assert envs["UMASK_SET"] == "002" - assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" - assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" - - -def test_add_from_all_sources(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_value") - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_value" - assert envs["USER_ENV"] == "test_value2" - assert envs["TZ"] == "Etc/UTC" - - -def test_user_add_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV2", "value": "test_value2"}, - ] - ) - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["MY_ENV"] == "test_value" - assert envs["MY_ENV2"] == "test_value2" - - -def test_user_add_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "MY_ENV", "value": "test_value"}, - {"name": "MY_ENV", "value": "test_value2"}, - ] - ) - - -def test_user_env_without_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_user_envs( - [ - {"name": "", "value": "test_value"}, - ] - ) - - -def test_user_env_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "TZ", "value": "test_value"}, - ] - ) - with pytest.raises(Exception): - render.render() - - -def test_user_env_try_to_overwrite_app_dev_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_user_envs( - [ - {"name": "PORT", "value": "test_value"}, - ] - ) - c1.environment.add_env("PORT", "test_value2") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): - mock_values["TZ"] = "Etc/UTC" - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("TZ", "test_value") - with pytest.raises(Exception): - render.render() - - -def test_app_dev_no_name(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.environment.add_env("", "test_value") - - -def test_app_dev_duplicate_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("PORT", "test_value") - with pytest.raises(Exception): - c1.environment.add_env("PORT", "test_value2") - - -def test_format_vars(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - c1.environment.add_env("APP_ENV", "test_$value") - c1.environment.add_env("APP_ENV_BOOL", True) - c1.environment.add_env("APP_ENV_INT", 10) - c1.environment.add_env("APP_ENV_FLOAT", 10.5) - c1.environment.add_user_envs( - [ - {"name": "USER_ENV", "value": "test_$value2"}, - ] - ) - - output = render.render() - envs = output["services"]["test_container"]["environment"] - assert envs["APP_ENV"] == "test_$$value" - assert envs["USER_ENV"] == "test_$$value2" - assert envs["APP_ENV_BOOL"] == "true" - assert envs["APP_ENV_INT"] == "10" - assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_healthcheck.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_healthcheck.py deleted file mode 100644 index fbd488ece4..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_healthcheck.py +++ /dev/null @@ -1,187 +0,0 @@ -import pytest - -from render import Render - - -@pytest.fixture -def mock_values(): - return { - "images": { - "test_image": { - "repository": "nginx", - "tag": "latest", - } - }, - } - - -def test_disable_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == {"disable": True} - - -def test_set_custom_test(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test("echo $1") - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": "echo $$1", - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_custom_test_array(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "10s", - "timeout": "5s", - "retries": 30, - "start_period": "10s", - } - - -def test_set_options(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) - c1.healthcheck.set_interval(9) - c1.healthcheck.set_timeout(8) - c1.healthcheck.set_retries(7) - c1.healthcheck.set_start_period(6) - output = render.render() - assert output["services"]["test_container"]["healthcheck"] == { - "test": ["CMD", "echo", "$$1"], - "interval": "9s", - "timeout": "8s", - "retries": 7, - "start_period": "6s", - } - - -def test_adding_test_when_disabled(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.disable() - with pytest.raises(Exception): - c1.healthcheck.set_custom_test("echo $1") - - -def test_not_adding_test(mock_values): - render = Render(mock_values) - render.add_container("test_container", "test_image") - with pytest.raises(Exception): - render.render() - - -def test_invalid_path(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - with pytest.raises(Exception): - c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) - - -def test_http_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("http", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa - ) - - -def test_curl_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" - ) - - -def test_curl_healthcheck_with_headers(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' - ) - - -def test_wget_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "wget --spider --quiet http://127.0.0.1:8080/health" - ) - - -def test_netcat_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("netcat", {"port": 8080}) - output = render.render() - assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" - - -def test_tcp_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("tcp", {"port": 8080}) - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" - ) - - -def test_redis_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("redis") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" - ) - - -def test_postgres_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("postgres") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" - ) - - -def test_mariadb_healthcheck(mock_values): - render = Render(mock_values) - c1 = render.add_container("test_container", "test_image") - c1.healthcheck.set_test("mariadb") - output = render.render() - assert ( - output["services"]["test_container"]["healthcheck"]["test"] - == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" - ) diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/validations.py b/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/validations.py deleted file mode 100644 index 13f155dfdb..0000000000 --- a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/validations.py +++ /dev/null @@ -1,227 +0,0 @@ -import re -import ipaddress - -try: - from .error import RenderError -except ImportError: - from error import RenderError - -OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") - - -def valid_sysctl_or_raise(sysctl: str, host_network: bool): - if not sysctl: - raise RenderError("Sysctl cannot be empty") - if host_network and sysctl.startswith("net."): - raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") - - valid_sysctls = [ - "kernel.msgmax", - "kernel.msgmnb", - "kernel.msgmni", - "kernel.sem", - "kernel.shmall", - "kernel.shmmax", - "kernel.shmmni", - "kernel.shm_rmid_forced", - ] - # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls - if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: - raise RenderError( - f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" - ) - return sysctl - - -def valid_redis_password_or_raise(password: str): - forbidden_chars = [" ", "'"] - for char in forbidden_chars: - if char in password: - raise RenderError(f"Redis password cannot contain [{char}]") - - -def valid_octal_mode_or_raise(mode: str): - mode = str(mode) - if not OCTAL_MODE_REGEX.match(mode): - raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") - return mode - - -def valid_host_path_propagation(propagation: str): - valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") - if propagation not in valid_propagations: - raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") - return propagation - - -def valid_portal_scheme_or_raise(scheme: str): - schemes = ("http", "https") - if scheme not in schemes: - raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") - return scheme - - -def valid_port_or_raise(port: int): - if port < 1 or port > 65535: - raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") - return port - - -def valid_ip_or_raise(ip: str): - try: - ipaddress.ip_address(ip) - except ValueError: - raise RenderError(f"Invalid IP address [{ip}]") - return ip - - -def valid_port_mode_or_raise(mode: str): - modes = ("ingress", "host") - if mode not in modes: - raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") - return mode - - -def valid_port_protocol_or_raise(protocol: str): - protocols = ("tcp", "udp") - if protocol not in protocols: - raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") - return protocol - - -def valid_depend_condition_or_raise(condition: str): - valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") - if condition not in valid_conditions: - raise RenderError( - f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" - ) - return condition - - -def valid_cgroup_perm_or_raise(cgroup_perm: str): - valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") - if cgroup_perm not in valid_cgroup_perms: - raise RenderError( - f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" - ) - return cgroup_perm - - -def allowed_dns_opt_or_raise(dns_opt: str): - disallowed_dns_opts = [] - if dns_opt in disallowed_dns_opts: - raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") - return dns_opt - - -def valid_http_path_or_raise(path: str): - path = _valid_path_or_raise(path) - return path - - -def valid_fs_path_or_raise(path: str): - # There is no reason to allow / as a path, - # either on host or in a container side. - if path == "/": - raise RenderError(f"Path [{path}] cannot be [/]") - path = _valid_path_or_raise(path) - return path - - -def _valid_path_or_raise(path: str): - if path == "": - raise RenderError(f"Path [{path}] cannot be empty") - if not path.startswith("/"): - raise RenderError(f"Path [{path}] must start with /") - if "//" in path: - raise RenderError(f"Path [{path}] cannot contain [//]") - return path - - -def allowed_device_or_raise(path: str): - disallowed_devices = ["/dev/dri", "/dev/bus/usb", "/dev/snd"] - if path in disallowed_devices: - raise RenderError(f"Device [{path}] is not allowed to be manually added.") - return path - - -def valid_network_mode_or_raise(mode: str, containers: list[str]): - valid_modes = ("host", "none") - if mode in valid_modes: - return mode - - if mode.startswith("service:"): - if mode[8:] not in containers: - raise RenderError(f"Service [{mode[8:]}] not found") - return mode - - raise RenderError( - f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" - ) - - -def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): - valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") - if policy not in valid_restart_policies: - raise RenderError( - f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" - ) - if policy != "on-failure" and maximum_retry_count != 0: - raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") - - if maximum_retry_count < 0: - raise RenderError("Maximum retry count must be a positive integer") - - return policy - - -def valid_cap_or_raise(cap: str): - valid_policies = ( - "ALL", - "AUDIT_CONTROL", - "AUDIT_READ", - "AUDIT_WRITE", - "BLOCK_SUSPEND", - "BPF", - "CHECKPOINT_RESTORE", - "CHOWN", - "DAC_OVERRIDE", - "DAC_READ_SEARCH", - "FOWNER", - "FSETID", - "IPC_LOCK", - "IPC_OWNER", - "KILL", - "LEASE", - "LINUX_IMMUTABLE", - "MAC_ADMIN", - "MAC_OVERRIDE", - "MKNOD", - "NET_ADMIN", - "NET_BIND_SERVICE", - "NET_BROADCAST", - "NET_RAW", - "PERFMON", - "SETFCAP", - "SETGID", - "SETPCAP", - "SETUID", - "SYS_ADMIN", - "SYS_BOOT", - "SYS_CHROOT", - "SYS_MODULE", - "SYS_NICE", - "SYS_PACCT", - "SYS_PTRACE", - "SYS_RAWIO", - "SYS_RESOURCE", - "SYS_TIME", - "SYS_TTY_CONFIG", - "SYSLOG", - "WAKE_ALARM", - ) - - if cap not in valid_policies: - raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") - - return cap diff --git a/trains/stable/wg-easy/1.1.1/README.md b/trains/stable/wg-easy/1.1.2/README.md similarity index 100% rename from trains/stable/wg-easy/1.1.1/README.md rename to trains/stable/wg-easy/1.1.2/README.md diff --git a/trains/stable/wg-easy/1.1.1/app.yaml b/trains/stable/wg-easy/1.1.2/app.yaml similarity index 88% rename from trains/stable/wg-easy/1.1.1/app.yaml rename to trains/stable/wg-easy/1.1.2/app.yaml index b878003f67..55aec87572 100644 --- a/trains/stable/wg-easy/1.1.1/app.yaml +++ b/trains/stable/wg-easy/1.1.2/app.yaml @@ -16,8 +16,8 @@ keywords: - wireguard - network - vpn -lib_version: 2.0.32 -lib_version_hash: 4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6 +lib_version: 2.1.0 +lib_version_hash: 6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291 maintainers: - email: dev@ixsystems.com name: truenas @@ -35,4 +35,4 @@ sources: - https://github.com/wg-easy/wg-easy title: WG Easy train: stable -version: 1.1.1 +version: 1.1.2 diff --git a/trains/stable/wg-easy/1.1.1/ix_values.yaml b/trains/stable/wg-easy/1.1.2/ix_values.yaml similarity index 100% rename from trains/stable/wg-easy/1.1.1/ix_values.yaml rename to trains/stable/wg-easy/1.1.2/ix_values.yaml diff --git a/trains/stable/wg-easy/1.1.1/migrations/migrate_from_kubernetes b/trains/stable/wg-easy/1.1.2/migrations/migrate_from_kubernetes similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migrate_from_kubernetes rename to trains/stable/wg-easy/1.1.2/migrations/migrate_from_kubernetes diff --git a/trains/stable/wg-easy/1.1.1/migrations/migration_helpers/__init__.py b/trains/stable/wg-easy/1.1.2/migrations/migration_helpers/__init__.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migration_helpers/__init__.py rename to trains/stable/wg-easy/1.1.2/migrations/migration_helpers/__init__.py diff --git a/trains/stable/wg-easy/1.1.1/migrations/migration_helpers/cpu.py b/trains/stable/wg-easy/1.1.2/migrations/migration_helpers/cpu.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migration_helpers/cpu.py rename to trains/stable/wg-easy/1.1.2/migrations/migration_helpers/cpu.py diff --git a/trains/stable/wg-easy/1.1.1/migrations/migration_helpers/dns_config.py b/trains/stable/wg-easy/1.1.2/migrations/migration_helpers/dns_config.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migration_helpers/dns_config.py rename to trains/stable/wg-easy/1.1.2/migrations/migration_helpers/dns_config.py diff --git a/trains/stable/wg-easy/1.1.1/migrations/migration_helpers/kubernetes_secrets.py b/trains/stable/wg-easy/1.1.2/migrations/migration_helpers/kubernetes_secrets.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migration_helpers/kubernetes_secrets.py rename to trains/stable/wg-easy/1.1.2/migrations/migration_helpers/kubernetes_secrets.py diff --git a/trains/stable/wg-easy/1.1.1/migrations/migration_helpers/memory.py b/trains/stable/wg-easy/1.1.2/migrations/migration_helpers/memory.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migration_helpers/memory.py rename to trains/stable/wg-easy/1.1.2/migrations/migration_helpers/memory.py diff --git a/trains/stable/wg-easy/1.1.1/migrations/migration_helpers/resources.py b/trains/stable/wg-easy/1.1.2/migrations/migration_helpers/resources.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migration_helpers/resources.py rename to trains/stable/wg-easy/1.1.2/migrations/migration_helpers/resources.py diff --git a/trains/stable/wg-easy/1.1.1/migrations/migration_helpers/storage.py b/trains/stable/wg-easy/1.1.2/migrations/migration_helpers/storage.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/migrations/migration_helpers/storage.py rename to trains/stable/wg-easy/1.1.2/migrations/migration_helpers/storage.py diff --git a/trains/stable/wg-easy/1.1.1/questions.yaml b/trains/stable/wg-easy/1.1.2/questions.yaml similarity index 100% rename from trains/stable/wg-easy/1.1.1/questions.yaml rename to trains/stable/wg-easy/1.1.2/questions.yaml diff --git a/trains/stable/wg-easy/1.1.1/templates/docker-compose.yaml b/trains/stable/wg-easy/1.1.2/templates/docker-compose.yaml similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/docker-compose.yaml rename to trains/stable/wg-easy/1.1.2/templates/docker-compose.yaml diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/__init__.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/__init__.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/__init__.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/__init__.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/configs.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/configs.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/configs.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/configs.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/container.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/container.py new file mode 100644 index 0000000000..701f64bfeb --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/container.py @@ -0,0 +1,339 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .configs import ContainerConfigs + from .depends import Depends + from .deploy import Deploy + from .devices import Devices + from .dns import Dns + from .environment import Environment + from .error import RenderError + from .formatter import escape_dollar, get_image_with_hashed_data + from .healthcheck import Healthcheck + from .labels import Labels + from .ports import Ports + from .restart import RestartPolicy + from .validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from .storage import Storage + from .sysctls import Sysctls +except ImportError: + from configs import ContainerConfigs + from depends import Depends + from deploy import Deploy + from devices import Devices + from dns import Dns + from environment import Environment + from error import RenderError + from formatter import escape_dollar, get_image_with_hashed_data + from healthcheck import Healthcheck + from labels import Labels + from ports import Ports + from restart import RestartPolicy + from validations import valid_network_mode_or_raise, valid_cap_or_raise, valid_pull_policy_or_raise + from storage import Storage + from sysctls import Sysctls + + +class Container: + def __init__(self, render_instance: "Render", name: str, image: str): + self._render_instance = render_instance + + self._name: str = name + self._image: str = self._resolve_image(image) + self._build_image: str = "" + self._pull_policy: str = "" + self._user: str = "" + self._tty: bool = False + self._stdin_open: bool = False + self._init: bool | None = None + self._read_only: bool | None = None + self._hostname: str = "" + self._cap_drop: set[str] = set(["ALL"]) # Drop all capabilities by default and add caps granularly + self._cap_add: set[str] = set() + self._security_opt: set[str] = set(["no-new-privileges"]) + self._privileged: bool = False + self._group_add: set[int | str] = set() + self._network_mode: str = "" + self._entrypoint: list[str] = [] + self._command: list[str] = [] + self._grace_period: int | None = None + self._shm_size: int | None = None + self._storage: Storage = Storage(self._render_instance) + self.sysctls: Sysctls = Sysctls(self._render_instance, self) + self.configs: ContainerConfigs = ContainerConfigs(self._render_instance, self._render_instance.configs) + self.deploy: Deploy = Deploy(self._render_instance) + self.networks: set[str] = set() + self.devices: Devices = Devices(self._render_instance) + self.environment: Environment = Environment(self._render_instance, self.deploy.resources) + self.dns: Dns = Dns(self._render_instance) + self.depends: Depends = Depends(self._render_instance) + self.healthcheck: Healthcheck = Healthcheck(self._render_instance) + self.labels: Labels = Labels(self._render_instance) + self.restart: RestartPolicy = RestartPolicy(self._render_instance) + self.ports: Ports = Ports(self._render_instance) + + self._auto_set_network_mode() + self._auto_add_labels() + self._auto_add_groups() + + def _auto_add_groups(self): + self.add_group(568) + + def _auto_set_network_mode(self): + if self._render_instance.values.get("network", {}).get("host_network", False): + self.set_network_mode("host") + + def _auto_add_labels(self): + labels = self._render_instance.values.get("labels", []) + if not labels: + return + + for label in labels: + containers = label.get("containers", []) + if not containers: + raise RenderError(f'Label [{label.get("key", "")}] must have at least one container') + + if self._name in containers: + self.labels.add_label(label["key"], label["value"]) + + def _resolve_image(self, image: str): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError( + f"Image [{image}] not found in values. " f"Available images: [{', '.join(images.keys())}]" + ) + repo = images[image].get("repository", "") + tag = images[image].get("tag", "") + + if not repo: + raise RenderError(f"Repository not found for image [{image}]") + if not tag: + raise RenderError(f"Tag not found for image [{image}]") + + return f"{repo}:{tag}" + + def build_image(self, content: list[str | None]): + dockerfile = f"FROM {self._image}\n" + for line in content: + if not line: + continue + if line.startswith("FROM"): + # TODO: This will also block multi-stage builds + # We can revisit this later if we need it + raise RenderError( + "FROM cannot be used in build image. Define the base image when creating the container." + ) + dockerfile += line + "\n" + + self._build_image = dockerfile + self._image = get_image_with_hashed_data(self._image, dockerfile) + + def set_pull_policy(self, pull_policy: str): + self._pull_policy = valid_pull_policy_or_raise(pull_policy) + + def set_user(self, user: int, group: int): + for i in (user, group): + if not isinstance(i, int) or i < 0: + raise RenderError(f"User/Group [{i}] is not valid") + self._user = f"{user}:{group}" + + def add_group(self, group: int | str): + if isinstance(group, str): + group = str(group).strip() + if group.isdigit(): + raise RenderError(f"Group is a number [{group}] but passed as a string") + + if group in self._group_add: + raise RenderError(f"Group [{group}] already added") + self._group_add.add(group) + + def get_current_groups(self) -> list[str]: + return [str(g) for g in self._group_add] + + def set_tty(self, enabled: bool = False): + self._tty = enabled + + def set_stdin(self, enabled: bool = False): + self._stdin_open = enabled + + def set_init(self, enabled: bool = False): + self._init = enabled + + def set_read_only(self, enabled: bool = False): + self._read_only = enabled + + def set_hostname(self, hostname: str): + self._hostname = hostname + + def set_grace_period(self, grace_period: int): + if grace_period < 0: + raise RenderError(f"Grace period [{grace_period}] cannot be negative") + self._grace_period = grace_period + + def set_privileged(self, enabled: bool = False): + self._privileged = enabled + + def clear_caps(self): + self._cap_add.clear() + self._cap_drop.clear() + + def add_caps(self, caps: list[str]): + for c in caps: + if c in self._cap_add: + raise RenderError(f"Capability [{c}] already added") + self._cap_add.add(valid_cap_or_raise(c)) + + def add_security_opt(self, opt: str): + if opt in self._security_opt: + raise RenderError(f"Security Option [{opt}] already added") + self._security_opt.add(opt) + + def remove_security_opt(self, opt: str): + self._security_opt.remove(opt) + + def set_network_mode(self, mode: str): + self._network_mode = valid_network_mode_or_raise(mode, self._render_instance.container_names()) + + def set_entrypoint(self, entrypoint: list[str]): + self._entrypoint = [escape_dollar(str(e)) for e in entrypoint] + + def set_command(self, command: list[str]): + self._command = [escape_dollar(str(e)) for e in command] + + def add_storage(self, mount_path: str, config: "IxStorage"): + self._storage.add(mount_path, config) + + def add_docker_socket(self, read_only: bool = True, mount_path: str = "/var/run/docker.sock"): + self.add_group(999) + self._storage._add_docker_socket(read_only, mount_path) + + def add_tun_device(self, read_only: bool = True, mount_path: str = "/dev/net/tun"): + self._storage._add_tun_device(read_only, mount_path) + + def add_snd_device(self): + self.add_group(29) + self.devices._add_snd_device() + + def set_shm_size_mb(self, size: int): + self._shm_size = size + + # Easily remove devices from the container + # Useful in dependencies like postgres and redis + # where there is no need to pass devices to them + def remove_devices(self): + self.deploy.resources.remove_devices() + self.devices.remove_devices() + + @property + def storage(self): + return self._storage + + def render(self) -> dict[str, Any]: + if self._network_mode and self.networks: + raise RenderError("Cannot set both [network_mode] and [networks]") + + result = { + "image": self._image, + "platform": "linux/amd64", + "tty": self._tty, + "stdin_open": self._stdin_open, + "restart": self.restart.render(), + } + + if self._pull_policy: + result["pull_policy"] = self._pull_policy + + if self.healthcheck.has_healthcheck(): + result["healthcheck"] = self.healthcheck.render() + + if self._hostname: + result["hostname"] = self._hostname + + if self._build_image: + result["build"] = {"tags": [self._image], "dockerfile_inline": self._build_image} + + if self.configs.has_configs(): + result["configs"] = self.configs.render() + + if self._init is not None: + result["init"] = self._init + + if self._read_only is not None: + result["read_only"] = self._read_only + + if self._grace_period is not None: + result["stop_grace_period"] = f"{self._grace_period}s" + + if self._user: + result["user"] = self._user + + if self.deploy.resources.has_gpus() or self.devices.has_gpus(): + self.add_group(44) # video + self.add_group(107) # render + + if self._group_add: + result["group_add"] = sorted(self._group_add, key=lambda g: (isinstance(g, str), g)) + + if self._shm_size is not None: + result["shm_size"] = f"{self._shm_size}M" + + if self._privileged is not None: + result["privileged"] = self._privileged + + if self._cap_drop: + result["cap_drop"] = sorted(self._cap_drop) + + if self._cap_add: + result["cap_add"] = sorted(self._cap_add) + + if self._security_opt: + result["security_opt"] = sorted(self._security_opt) + + if self._network_mode: + result["network_mode"] = self._network_mode + + if self.sysctls.has_sysctls(): + result["sysctls"] = self.sysctls.render() + + if self._network_mode != "host": + if self.ports.has_ports(): + result["ports"] = self.ports.render() + + if self._entrypoint: + result["entrypoint"] = self._entrypoint + + if self._command: + result["command"] = self._command + + if self.devices.has_devices(): + result["devices"] = self.devices.render() + + if self.deploy.has_deploy(): + result["deploy"] = self.deploy.render() + + if self.environment.has_variables(): + result["environment"] = self.environment.render() + + if self.labels.has_labels(): + result["labels"] = self.labels.render() + + if self.dns.has_dns_nameservers(): + result["dns"] = self.dns.render_dns_nameservers() + + if self.dns.has_dns_searches(): + result["dns_search"] = self.dns.render_dns_searches() + + if self.dns.has_dns_opts(): + result["dns_opt"] = self.dns.render_dns_opts() + + if self.depends.has_dependencies(): + result["depends_on"] = self.depends.render() + + if self._storage.has_mounts(): + result["volumes"] = self._storage.render() + + return result diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/depends.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/depends.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/depends.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/depends.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/deploy.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deploy.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/deploy.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deploy.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps.py new file mode 100644 index 0000000000..e96849f979 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .deps_postgres import PostgresContainer, PostgresConfig + from .deps_redis import RedisContainer, RedisConfig + from .deps_mariadb import MariadbContainer, MariadbConfig + from .deps_perms import PermsContainer +except ImportError: + from deps_postgres import PostgresContainer, PostgresConfig + from deps_redis import RedisContainer, RedisConfig + from deps_mariadb import MariadbContainer, MariadbConfig + from deps_perms import PermsContainer + + +class Deps: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def perms(self, name: str): + return PermsContainer(self._render_instance, name) + + def postgres(self, name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer): + return PostgresContainer(self._render_instance, name, image, config, perms_instance) + + def redis(self, name: str, image: str, config: RedisConfig, perms_instance: PermsContainer): + return RedisContainer(self._render_instance, name, image, config, perms_instance) + + def mariadb(self, name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer): + return MariadbContainer(self._render_instance, name, image, config, perms_instance) diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py new file mode 100644 index 0000000000..baf863b370 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_mariadb.py @@ -0,0 +1,65 @@ +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class MariadbConfig(TypedDict): + user: str + password: str + database: str + root_password: NotRequired[str] + port: NotRequired[int] + auto_upgrade: NotRequired[bool] + volume: "IxStorage" + + +class MariadbContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: MariadbConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for mariadb") + + port = valid_port_or_raise(config.get("port") or 3306) + root_password = config.get("root_password") or config["password"] + auto_upgrade = config.get("auto_upgrade", True) + + c = self._render_instance.add_container(name, image) + c.set_user(999, 999) + c.healthcheck.set_test("mariadb") + c.remove_devices() + + c.add_storage("/var/lib/mysql", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_mariadb_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + c.environment.add_env("MARIADB_USER", config["user"]) + c.environment.add_env("MARIADB_PASSWORD", config["password"]) + c.environment.add_env("MARIADB_ROOT_PASSWORD", root_password) + c.environment.add_env("MARIADB_DATABASE", config["database"]) + c.environment.add_env("MARIADB_AUTO_UPGRADE", str(auto_upgrade).lower()) + c.set_command(["--port", str(port)]) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_perms.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_perms.py new file mode 100644 index 0000000000..cdc5a3820a --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_perms.py @@ -0,0 +1,252 @@ +import json +import pathlib +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .validations import valid_octal_mode_or_raise, valid_fs_path_or_raise +except ImportError: + from error import RenderError + from validations import valid_octal_mode_or_raise, valid_fs_path_or_raise + + +class PermsContainer: + def __init__(self, render_instance: "Render", name: str): + self._render_instance = render_instance + self._name = name + self.actions: set[str] = set() + self.parsed_configs: list[dict] = [] + + def add_or_skip_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + identifier = self.normalize_identifier_for_path(identifier) + if identifier in self.actions: + raise RenderError(f"Action with id [{identifier}] already used for another permission action") + + parsed_action = self.parse_action(identifier, volume_config, action_config) + if parsed_action: + self.parsed_configs.append(parsed_action) + self.actions.add(identifier) + + def parse_action(self, identifier: str, volume_config: "IxStorage", action_config: dict): + valid_modes = [ + "always", # Always set permissions, without checking. + "check", # Checks if permissions are correct, and set them if not. + ] + mode = action_config.get("mode", "check") + uid = action_config.get("uid", None) + gid = action_config.get("gid", None) + chmod = action_config.get("chmod", None) + recursive = action_config.get("recursive", False) + mount_path = pathlib.Path("/mnt/permission", identifier).as_posix() + is_temporary = False + + vol_type = volume_config.get("type", "") + match vol_type: + case "temporary": + # If it is a temporary volume, we force auto permissions + # and set is_temporary to True, so it will be cleaned up + is_temporary = True + recursive = True + case "volume": + if not volume_config.get("volume_config", {}).get("auto_permissions", False): + return None + case "host_path": + host_path_config = volume_config.get("host_path_config", {}) + # Skip when ACL enabled + if host_path_config.get("acl_enable", False): + return None + if not host_path_config.get("auto_permissions", False): + return None + case "ix_volume": + ix_vol_config = volume_config.get("ix_volume_config", {}) + # Skip when ACL enabled + if ix_vol_config.get("acl_enable", False): + return None + # For ix_volumes, we default to auto_permissions = True + if not ix_vol_config.get("auto_permissions", True): + return None + case _: + # Skip for other types + return None + + if mode not in valid_modes: + raise RenderError(f"Expected [mode] to be one of [{', '.join(valid_modes)}], got [{mode}]") + if not isinstance(uid, int) or not isinstance(gid, int): + raise RenderError("Expected [uid] and [gid] to be set when [auto_permissions] is enabled") + if chmod is not None: + chmod = valid_octal_mode_or_raise(chmod) + + mount_path = valid_fs_path_or_raise(mount_path) + return { + "mount_path": mount_path, + "volume_config": volume_config, + "action_data": { + "mount_path": mount_path, + "is_temporary": is_temporary, + "identifier": identifier, + "recursive": recursive, + "mode": mode, + "uid": uid, + "gid": gid, + "chmod": chmod, + }, + } + + def normalize_identifier_for_path(self, identifier: str): + return identifier.rstrip("/").lstrip("/").lower().replace("/", "_").replace(".", "-").replace(" ", "-") + + def has_actions(self): + return bool(self.actions) + + def activate(self): + if len(self.parsed_configs) != len(self.actions): + raise RenderError("Number of actions and parsed configs does not match") + + if not self.has_actions(): + raise RenderError("No actions added. Check if there are actions before activating") + + # Add the container and set it up + c = self._render_instance.add_container(self._name, "python_permissions_image") + c.set_user(0, 0) + c.add_caps(["CHOWN", "FOWNER", "DAC_OVERRIDE"]) + c.set_network_mode("none") + + # Don't attach any devices + c.remove_devices() + + c.deploy.resources.set_profile("medium") + c.restart.set_policy("on-failure", maximum_retry_count=1) + c.healthcheck.disable() + + c.set_entrypoint(["python3", "/script/run.py"]) + script = "#!/usr/bin/env python3\n" + script += get_script() + c.configs.add("permissions_run_script", script, "/script/run.py", "0700") + + actions_data: list[dict] = [] + for parsed in self.parsed_configs: + c.add_storage(parsed["mount_path"], parsed["volume_config"]) + actions_data.append(parsed["action_data"]) + + actions_data_json = json.dumps(actions_data) + c.configs.add("permissions_actions_data", actions_data_json, "/script/actions.json", "0500") + + +def get_script(): + return """ +import os +import json +import time +import shutil + +with open("/script/actions.json", "r") as f: + actions_data = json.load(f) + +if not actions_data: + # If this script is called, there should be actions data + raise ValueError("No actions data found") + +def fix_perms(path, chmod, recursive=False): + print(f"Changing permissions{' recursively ' if recursive else ' '}to {chmod} on: [{path}]") + os.chmod(path, int(chmod, 8)) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chmod(os.path.join(root, f), int(chmod, 8)) + print("Permissions after changes:") + print_chmod_stat() + +def fix_owner(path, uid, gid, recursive=False): + print(f"Changing ownership{' recursively ' if recursive else ' '}to {uid}:{gid} on: [{path}]") + os.chown(path, uid, gid) + if recursive: + for root, dirs, files in os.walk(path): + for f in files: + os.chown(os.path.join(root, f), uid, gid) + print("Ownership after changes:") + print_chown_stat() + +def print_chown_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Ownership: [{curr_stat.st_uid}:{curr_stat.st_gid}]") + +def print_chmod_stat(): + curr_stat = os.stat(action["mount_path"]) + print(f"Permissions: [{oct(curr_stat.st_mode)[3:]}]") + +def print_chown_diff(curr_stat, uid, gid): + print(f"Ownership: wanted [{uid}:{gid}], got [{curr_stat.st_uid}:{curr_stat.st_gid}].") + +def print_chmod_diff(curr_stat, mode): + print(f"Permissions: wanted [{mode}], got [{oct(curr_stat.st_mode)[3:]}].") + +def perform_action(action): + start_time = time.time() + print(f"=== Applying configuration on volume with identifier [{action['identifier']}] ===") + + if not os.path.isdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not a directory, skipping...") + return + + if action["is_temporary"]: + print(f"Path [{action['mount_path']}] is a temporary directory, ensuring it is empty...") + for item in os.listdir(action["mount_path"]): + item_path = os.path.join(action["mount_path"], item) + + # Exclude the safe directory, where we can use to mount files temporarily + if os.path.basename(item_path) == "ix-safe": + continue + if os.path.isdir(item_path): + shutil.rmtree(item_path) + else: + os.remove(item_path) + + if not action["is_temporary"] and os.listdir(action["mount_path"]): + print(f"Path [{action['mount_path']}] is not empty, skipping...") + return + + print(f"Current Ownership and Permissions on [{action['mount_path']}]:") + curr_stat = os.stat(action["mount_path"]) + print_chown_diff(curr_stat, action["uid"], action["gid"]) + print_chmod_diff(curr_stat, action["chmod"]) + print("---") + + if action["mode"] == "always": + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + return + + elif action["mode"] == "check": + if curr_stat.st_uid != action["uid"] or curr_stat.st_gid != action["gid"]: + print("Ownership is incorrect. Fixing...") + fix_owner(action["mount_path"], action["uid"], action["gid"], action["recursive"]) + else: + print("Ownership is correct. Skipping...") + + if not action["chmod"]: + print("Skipping permissions check, chmod is falsy") + else: + if oct(curr_stat.st_mode)[3:] != action["chmod"]: + print("Permissions are incorrect. Fixing...") + fix_perms(action["mount_path"], action["chmod"], action["recursive"]) + else: + print("Permissions are correct. Skipping...") + + print(f"Time taken: {(time.time() - start_time) * 1000:.2f}ms") + print(f"=== Finished applying configuration on volume with identifier [{action['identifier']}] ==") + print() + +if __name__ == "__main__": + start_time = time.time() + for action in actions_data: + perform_action(action) + print(f"Total time taken: {(time.time() - start_time) * 1000:.2f}ms") +""" diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_postgres.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_postgres.py new file mode 100644 index 0000000000..c40e900d07 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_postgres.py @@ -0,0 +1,279 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise + + +class PostgresConfig(TypedDict): + user: str + password: str + database: str + port: NotRequired[int] + volume: "IxStorage" + + +MAX_POSTGRES_VERSION = 17 + + +class PostgresContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: PostgresConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + self._data_dir = "/var/lib/postgresql/data" + self._upgrade_name = f"{self._name}_upgrade" + self._upgrade_container = None + + for key in ("user", "password", "database", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for postgres") + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + + c.set_user(999, 999) + c.healthcheck.set_test("postgres") + c.remove_devices() + c.add_storage(self._data_dir, config["volume"]) + + common_variables = { + "POSTGRES_USER": config["user"], + "POSTGRES_PASSWORD": config["password"], + "POSTGRES_DB": config["database"], + "POSTGRES_PORT": port, + } + + for k, v in common_variables.items(): + c.environment.add_env(k, v) + + perms_instance.add_or_skip_action( + f"{self._name}_postgres_data", config["volume"], {"uid": 999, "gid": 999, "mode": "check"} + ) + + repo = self._get_repo(image) + # eg we don't want to handle upgrades of pg_vector at the moment + if repo == "postgres": + target_major_version = self._get_target_version(image) + upg = self._render_instance.add_container(self._upgrade_name, image) + upg.build_image(get_build_manifest()) + upg.set_entrypoint(["/bin/bash", "-c", "/upgrade.sh"]) + upg.configs.add("pg_container_upgrade.sh", get_upgrade_script(), "/upgrade.sh", "0755") + upg.restart.set_policy("on-failure", 1) + upg.set_user(999, 999) + upg.healthcheck.disable() + upg.remove_devices() + upg.add_storage(self._data_dir, config["volume"]) + for k, v in common_variables.items(): + upg.environment.add_env(k, v) + + upg.environment.add_env("TARGET_VERSION", target_major_version) + upg.environment.add_env("DATA_DIR", self._data_dir) + + self._upgrade_container = upg + + c.depends.add_dependency(self._upgrade_name, "service_completed_successfully") + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + @property + def container(self): + return self._container + + def add_dependency(self, container_name: str, condition: str): + self._container.depends.add_dependency(container_name, condition) + if self._upgrade_container: + self._upgrade_container.depends.add_dependency(container_name, condition) + + def _get_port(self): + return self._config.get("port") or 5432 + + def _get_repo(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + repo = images[image].get("repository", "") + if not repo: + raise RenderError("Could not determine repo") + return repo + + def _get_target_version(self, image): + images = self._render_instance.values["images"] + if image not in images: + raise RenderError(f"Image [{image}] not found in values. Available images: [{', '.join(images.keys())}]") + tag = images[image].get("tag", "") + tag = str(tag) # Account for tags like 16.6 + target_major_version = tag.split(".")[0] + + try: + target_major_version = int(target_major_version) + except ValueError: + raise RenderError(f"Could not determine target major version from tag [{tag}]") + + if target_major_version > MAX_POSTGRES_VERSION: + raise RenderError(f"Postgres version [{target_major_version}] is not supported") + + return target_major_version + + def get_url(self, variant: str): + user = urllib.parse.quote_plus(self._config["user"]) + password = urllib.parse.quote_plus(self._config["password"]) + creds = f"{user}:{password}" + addr = f"{self._name}:{self._get_port()}" + db = self._config["database"] + + match variant: + case "postgres": + return f"postgres://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql": + return f"postgresql://{creds}@{addr}/{db}?sslmode=disable" + case "postgresql_no_creds": + return f"postgresql://{addr}/{db}?sslmode=disable" + case "host_port": + return addr + case _: + raise RenderError(f"Expected [variant] to be one of [postgres, postgresql], got [{variant}]") + + +def get_build_manifest() -> list[str | None]: + return [ + f"RUN apt-get update && apt-get install -y {' '.join(get_upgrade_packages())}", + "WORKDIR /tmp", + ] + + +def get_upgrade_packages(): + return [ + "rsync", + "postgresql-13", + "postgresql-14", + "postgresql-15", + "postgresql-16", + ] + + +def get_upgrade_script(): + return """ +#!/bin/bash +set -euo pipefail + +get_bin_path() { + local version=$1 + echo "/usr/lib/postgresql/$version/bin" +} + +log() { + echo "[ix-postgres-upgrade] - [$(date +'%Y-%m-%d %H:%M:%S')] - $1" +} + +check_writable() { + local path=$1 + if [ ! -w "$path" ]; then + log "$path is not writable" + exit 1 + fi +} + +check_writable "$DATA_DIR" + +# Don't do anything if its a fresh install. +if [ ! -f "$DATA_DIR/PG_VERSION" ]; then + log "File $DATA_DIR/PG_VERSION does not exist. Assuming this is a fresh install." + exit 0 +fi + +# Don't do anything if we're already at the target version. +OLD_VERSION=$(cat "$DATA_DIR/PG_VERSION") +log "Current version: $OLD_VERSION" +log "Target version: $TARGET_VERSION" +if [ "$OLD_VERSION" -eq "$TARGET_VERSION" ]; then + log "Already at target version $TARGET_VERSION" + exit 0 +fi + +# Fail if we're downgrading. +if [ "$OLD_VERSION" -gt "$TARGET_VERSION" ]; then + log "Cannot downgrade from $OLD_VERSION to $TARGET_VERSION" + exit 1 +fi + +export OLD_PG_BINARY=$(get_bin_path "$OLD_VERSION") +if [ ! -f "$OLD_PG_BINARY/pg_upgrade" ]; then + log "File $OLD_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_PG_BINARY=$(get_bin_path "$TARGET_VERSION") +if [ ! -f "$NEW_PG_BINARY/pg_upgrade" ]; then + log "File $NEW_PG_BINARY/pg_upgrade does not exist." + exit 1 +fi + +export NEW_DATA_DIR="/tmp/new-data-dir" +if [ -d "$NEW_DATA_DIR" ]; then + log "Directory $NEW_DATA_DIR already exists." + exit 1 +fi + +export PGUSER="$POSTGRES_USER" +log "Creating new data dir and initializing..." +PGDATA="$NEW_DATA_DIR" eval "initdb --username=$POSTGRES_USER --pwfile=<(echo $POSTGRES_PASSWORD)" + +timestamp=$(date +%Y%m%d%H%M%S) +backup_name="backup-$timestamp-$OLD_VERSION-$TARGET_VERSION.tar.gz" +log "Backing up $DATA_DIR to $NEW_DATA_DIR/$backup_name" +tar -czf "$NEW_DATA_DIR/$backup_name" "$DATA_DIR" + +log "Using old pg_upgrade [$OLD_PG_BINARY/pg_upgrade]" +log "Using new pg_upgrade [$NEW_PG_BINARY/pg_upgrade]" +log "Checking upgrade compatibility of $OLD_VERSION to $TARGET_VERSION..." + +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql \ + --check + +log "Compatibility check passed." + +log "Upgrading from $OLD_VERSION to $TARGET_VERSION..." +"$NEW_PG_BINARY"/pg_upgrade \ + --old-bindir="$OLD_PG_BINARY" \ + --new-bindir="$NEW_PG_BINARY" \ + --old-datadir="$DATA_DIR" \ + --new-datadir="$NEW_DATA_DIR" \ + --socketdir /var/run/postgresql + +log "Upgrade complete." + +log "Copying old pg_hba.conf to new pg_hba.conf" +# We need to carry this over otherwise +cp "$DATA_DIR/pg_hba.conf" "$NEW_DATA_DIR/pg_hba.conf" + +log "Replacing contents of $DATA_DIR with contents of $NEW_DATA_DIR (including the backup)." +rsync --archive --delete "$NEW_DATA_DIR/" "$DATA_DIR/" + +log "Removing $NEW_DATA_DIR." +rm -rf "$NEW_DATA_DIR" + +log "Done." +""" diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_redis.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_redis.py new file mode 100644 index 0000000000..d49ebe7683 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/deps_redis.py @@ -0,0 +1,71 @@ +import urllib.parse +from typing import TYPE_CHECKING, TypedDict, NotRequired + +if TYPE_CHECKING: + from render import Render + from storage import IxStorage + +try: + from .error import RenderError + from .deps_perms import PermsContainer + from .validations import valid_port_or_raise, valid_redis_password_or_raise +except ImportError: + from error import RenderError + from deps_perms import PermsContainer + from validations import valid_port_or_raise, valid_redis_password_or_raise + + +class RedisConfig(TypedDict): + password: str + port: NotRequired[int] + volume: "IxStorage" + + +class RedisContainer: + def __init__( + self, render_instance: "Render", name: str, image: str, config: RedisConfig, perms_instance: PermsContainer + ): + self._render_instance = render_instance + self._name = name + self._config = config + + for key in ("password", "volume"): + if key not in config: + raise RenderError(f"Expected [{key}] to be set for redis") + + valid_redis_password_or_raise(config["password"]) + + port = valid_port_or_raise(self._get_port()) + + c = self._render_instance.add_container(name, image) + c.set_user(1001, 0) + c.healthcheck.set_test("redis") + c.remove_devices() + + c.add_storage("/bitnami/redis/data", config["volume"]) + perms_instance.add_or_skip_action( + f"{self._name}_redis_data", config["volume"], {"uid": 1001, "gid": 0, "mode": "check"} + ) + + c.environment.add_env("ALLOW_EMPTY_PASSWORD", "no") + c.environment.add_env("REDIS_PASSWORD", config["password"]) + c.environment.add_env("REDIS_PORT_NUMBER", port) + + # Store container for further configuration + # For example: c.depends.add_dependency("other_container", "service_started") + self._container = c + + def _get_port(self): + return self._config.get("port") or 6379 + + def get_url(self, variant: str): + addr = f"{self._name}:{self._get_port()}" + password = urllib.parse.quote_plus(self._config["password"]) + + match variant: + case "redis": + return f"redis://default:{password}@{addr}" + + @property + def container(self): + return self._container diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/device.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/device.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/device.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/device.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/devices.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/devices.py new file mode 100644 index 0000000000..b6139371ee --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/devices.py @@ -0,0 +1,68 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .device import Device +except ImportError: + from error import RenderError + from device import Device + + +class Devices: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._devices: set[Device] = set() + + # Tracks all container device paths to make sure they are not duplicated + self._container_device_paths: set[str] = set() + # Scan values for devices we should automatically add + # for example /dev/dri for gpus + self._auto_add_devices_from_values() + + def _auto_add_devices_from_values(self): + resources = self._render_instance.values.get("resources", {}) + + if resources.get("gpus", {}).get("use_all_gpus", False): + self.add_device("/dev/dri", "/dev/dri", allow_disallowed=True) + if resources["gpus"].get("kfd_device_exists", False): + self.add_device("/dev/kfd", "/dev/kfd", allow_disallowed=True) # AMD ROCm + + def add_device(self, host_device: str, container_device: str, cgroup_perm: str = "", allow_disallowed=False): + # Host device can be mapped to multiple container devices, + # so we only make sure container devices are not duplicated + if container_device in self._container_device_paths: + raise RenderError(f"Device with container path [{container_device}] already added") + + self._devices.add(Device(host_device, container_device, cgroup_perm, allow_disallowed)) + self._container_device_paths.add(container_device) + + def add_usb_bus(self): + self.add_device("/dev/bus/usb", "/dev/bus/usb", allow_disallowed=True) + + def _add_snd_device(self): + self.add_device("/dev/snd", "/dev/snd", allow_disallowed=True) + + def has_devices(self): + return len(self._devices) > 0 + + # Mainly will be used from dependencies + # There is no reason to pass devices to + # redis or postgres for example + def remove_devices(self): + self._devices.clear() + self._container_device_paths.clear() + + # Check if there are any gpu devices + # Used to determine if we should add groups + # like 'video' to the container + def has_gpus(self): + for d in self._devices: + if d.host_device == "/dev/dri": + return True + return False + + def render(self) -> list[str]: + return sorted([d.render() for d in self._devices]) diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/dns.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/dns.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/dns.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/dns.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/environment.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/environment.py new file mode 100644 index 0000000000..056763ea80 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/environment.py @@ -0,0 +1,112 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render +try: + from .error import RenderError + from .formatter import escape_dollar + from .resources import Resources +except ImportError: + from error import RenderError + from formatter import escape_dollar + from resources import Resources + + +class Environment: + def __init__(self, render_instance: "Render", resources: Resources): + self._render_instance = render_instance + self._resources = resources + # Stores variables that user defined + self._user_vars: dict[str, Any] = {} + # Stores variables that are automatically added (based on values) + self._auto_variables: dict[str, Any] = {} + # Stores variables that are added by the application developer + self._app_dev_variables: dict[str, Any] = {} + + self._skip_generic_variables: bool = render_instance.values.get("skip_generic_variables", False) + + self._auto_add_variables_from_values() + + def _auto_add_variables_from_values(self): + if not self._skip_generic_variables: + self._add_generic_variables() + self._add_nvidia_variables() + + def _add_generic_variables(self): + self._auto_variables["TZ"] = self._render_instance.values.get("TZ", "Etc/UTC") + self._auto_variables["UMASK"] = self._render_instance.values.get("UMASK", "002") + self._auto_variables["UMASK_SET"] = self._render_instance.values.get("UMASK", "002") + + run_as = self._render_instance.values.get("run_as", {}) + user = run_as.get("user") + group = run_as.get("group") + if user: + self._auto_variables["PUID"] = user + self._auto_variables["UID"] = user + self._auto_variables["USER_ID"] = user + if group: + self._auto_variables["PGID"] = group + self._auto_variables["GID"] = group + self._auto_variables["GROUP_ID"] = group + + def _add_nvidia_variables(self): + if self._resources._nvidia_ids: + self._auto_variables["NVIDIA_DRIVER_CAPABILITIES"] = "all" + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = ",".join(sorted(self._resources._nvidia_ids)) + else: + self._auto_variables["NVIDIA_VISIBLE_DEVICES"] = "void" + + def _format_value(self, v: Any) -> str: + value = str(v) + + # str(bool) returns "True" or "False", + # but we want "true" or "false" + if isinstance(v, bool): + value = value.lower() + return value + + def add_env(self, name: str, value: Any): + if not name: + raise RenderError(f"Environment variable name cannot be empty. [{name}]") + if name in self._app_dev_variables.keys(): + raise RenderError( + f"Found duplicate environment variable [{name}] in application developer environment variables." + ) + self._app_dev_variables[name] = value + + def add_user_envs(self, user_env: list[dict]): + for item in user_env: + if not item.get("name"): + raise RenderError(f"Environment variable name cannot be empty. [{item}]") + if item["name"] in self._user_vars.keys(): + raise RenderError( + f"Found duplicate environment variable [{item['name']}] in user environment variables." + ) + self._user_vars[item["name"]] = item.get("value") + + def has_variables(self): + return len(self._auto_variables) > 0 or len(self._user_vars) > 0 or len(self._app_dev_variables) > 0 + + def render(self): + result: dict[str, str] = {} + + # Add envs from auto variables + result.update({k: self._format_value(v) for k, v in self._auto_variables.items()}) + + # Track defined keys for faster lookup + defined_keys = set(result.keys()) + + # Add envs from application developer (prohibit overwriting auto variables) + for k, v in self._app_dev_variables.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined automatically from the library.") + result[k] = self._format_value(v) + defined_keys.add(k) + + # Add envs from user (prohibit overwriting app developer envs and auto variables) + for k, v in self._user_vars.items(): + if k in defined_keys: + raise RenderError(f"Environment variable [{k}] is already defined from the application developer.") + result[k] = self._format_value(v) + + return {k: escape_dollar(v) for k, v in result.items()} diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/error.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/error.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/error.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/error.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/formatter.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/formatter.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/formatter.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/formatter.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/functions.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/functions.py new file mode 100644 index 0000000000..7d082d8c46 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/functions.py @@ -0,0 +1,149 @@ +import re +import copy +import bcrypt +import secrets +from base64 import b64encode +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .volume_sources import HostPathSource, IxVolumeSource +except ImportError: + from error import RenderError + from volume_sources import HostPathSource, IxVolumeSource + + +class Functions: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + + def _bcrypt_hash(self, password): + hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + return hashed + + def _htpasswd(self, username, password): + hashed = self._bcrypt_hash(password) + return username + ":" + hashed + + def _secure_string(self, length): + return secrets.token_urlsafe(length) + + def _basic_auth(self, username, password): + return b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8") + + def _basic_auth_header(self, username, password): + return f"Basic {self._basic_auth(username, password)}" + + def _fail(self, message): + raise RenderError(message) + + def _camel_case(self, string): + return string.title() + + def _auto_cast(self, value): + try: + return int(value) + except ValueError: + pass + + try: + return float(value) + except ValueError: + pass + + if value.lower() in ["true", "false"]: + return value.lower() == "true" + + return value + + def _match_regex(self, value, regex): + if not re.match(regex, value): + return False + return True + + def _must_match_regex(self, value, regex): + if not self._match_regex(value, regex): + raise RenderError(f"Expected [{value}] to match [{regex}]") + return value + + def _is_boolean(self, string): + return string.lower() in ["true", "false"] + + def _is_number(self, string): + try: + float(string) + return True + except ValueError: + return False + + def _copy_dict(self, dict): + return copy.deepcopy(dict) + + def _merge_dicts(self, *dicts): + merged_dict = {} + for dictionary in dicts: + merged_dict.update(dictionary) + return merged_dict + + def _disallow_chars(self, string: str, chars: list[str], key: str): + for char in chars: + if char in string: + raise RenderError(f"Disallowed character [{char}] in [{key}]") + return string + + def _or_default(self, value, default): + if not value: + return default + return value + + def _temp_config(self, name): + if not name: + raise RenderError("Expected [name] to be set when calling [temp_config].") + return {"type": "temporary", "volume_config": {"volume_name": name}} + + def _get_host_path(self, storage): + source_type = storage.get("type", "") + if not source_type: + raise RenderError("Expected [type] to be set for volume mounts.") + + match source_type: + case "host_path": + mount_config = storage.get("host_path_config") + if mount_config is None: + raise RenderError("Expected [host_path_config] to be set for [host_path] type.") + host_source = HostPathSource(self._render_instance, mount_config).get() + return host_source + case "ix_volume": + mount_config = storage.get("ix_volume_config") + if mount_config is None: + raise RenderError("Expected [ix_volume_config] to be set for [ix_volume] type.") + ix_source = IxVolumeSource(self._render_instance, mount_config).get() + return ix_source + case _: + raise RenderError(f"Storage type [{source_type}] does not support host path.") + + def func_map(self): + # TODO: Check what is no longer used and remove + return { + "auto_cast": self._auto_cast, + "basic_auth_header": self._basic_auth_header, + "basic_auth": self._basic_auth, + "bcrypt_hash": self._bcrypt_hash, + "camel_case": self._camel_case, + "copy_dict": self._copy_dict, + "fail": self._fail, + "htpasswd": self._htpasswd, + "is_boolean": self._is_boolean, + "is_number": self._is_number, + "match_regex": self._match_regex, + "merge_dicts": self._merge_dicts, + "must_match_regex": self._must_match_regex, + "secure_string": self._secure_string, + "disallow_chars": self._disallow_chars, + "get_host_path": self._get_host_path, + "or_default": self._or_default, + "temp_config": self._temp_config, + } diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/healthcheck.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/healthcheck.py new file mode 100644 index 0000000000..0805329284 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/healthcheck.py @@ -0,0 +1,203 @@ +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .formatter import escape_dollar + from .validations import valid_http_path_or_raise +except ImportError: + from error import RenderError + from formatter import escape_dollar + from validations import valid_http_path_or_raise + + +class Healthcheck: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._test: str | list[str] = "" + self._interval_sec: int = 10 + self._timeout_sec: int = 5 + self._retries: int = 30 + self._start_period_sec: int = 10 + self._disabled: bool = False + self._use_built_in: bool = False + + def _get_test(self): + if isinstance(self._test, str): + return escape_dollar(self._test) + + return [escape_dollar(t) for t in self._test] + + def disable(self): + self._disabled = True + + def use_built_in(self): + self._use_built_in = True + + def set_custom_test(self, test: str | list[str]): + if self._disabled: + raise RenderError("Cannot set custom test when healthcheck is disabled") + self._test = test + + def set_test(self, variant: str, config: dict | None = None): + config = config or {} + self.set_custom_test(test_mapping(variant, config)) + + def set_interval(self, interval: int): + self._interval_sec = interval + + def set_timeout(self, timeout: int): + self._timeout_sec = timeout + + def set_retries(self, retries: int): + self._retries = retries + + def set_start_period(self, start_period: int): + self._start_period_sec = start_period + + def has_healthcheck(self): + return not self._use_built_in + + def render(self): + if self._use_built_in: + return RenderError("Should not be called when built in healthcheck is used") + + if self._disabled: + return {"disable": True} + + if not self._test: + raise RenderError("Healthcheck test is not set") + + return { + "test": self._get_test(), + "interval": f"{self._interval_sec}s", + "timeout": f"{self._timeout_sec}s", + "retries": self._retries, + "start_period": f"{self._start_period_sec}s", + } + + +def test_mapping(variant: str, config: dict | None = None) -> str: + config = config or {} + tests = { + "curl": curl_test, + "wget": wget_test, + "http": http_test, + "netcat": netcat_test, + "tcp": tcp_test, + "redis": redis_test, + "postgres": postgres_test, + "mariadb": mariadb_test, + } + + if variant not in tests: + raise RenderError(f"Test variant [{variant}] is not valid. Valid options are: [{', '.join(tests.keys())}]") + + return tests[variant](config) + + +def get_key(config: dict, key: str, default: Any, required: bool): + if not config.get(key): + if not required: + return default + raise RenderError(f"Expected [{key}] to be set") + return config[key] + + +def curl_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--insecure") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for curl test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "curl --silent --output /dev/null --show-error --fail" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def wget_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + scheme = get_key(config, "scheme", "http", False) + host = get_key(config, "host", "127.0.0.1", False) + headers = get_key(config, "headers", [], False) + + opts = [] + if scheme == "https": + opts.append("--no-check-certificate") + + for header in headers: + if not header[0] or not header[1]: + raise RenderError("Expected [header] to be a list of two items for wget test") + opts.append(f'--header "{header[0]}: {header[1]}"') + + cmd = "wget --spider --quiet" + if opts: + cmd += f" {' '.join(opts)}" + cmd += f" {scheme}://{host}:{port}{path}" + return cmd + + +def http_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + path = valid_http_path_or_raise(get_key(config, "path", "/", False)) + host = get_key(config, "host", "127.0.0.1", False) + + return f"""/bin/bash -c 'exec {{hc_fd}}<>/dev/tcp/{host}/{port} && echo -e "GET {path} HTTP/1.1\\r\\nHost: {host}\\r\\nConnection: close\\r\\n\\r\\n" >&${{hc_fd}} && cat <&${{hc_fd}} | grep "HTTP" | grep -q "200"'""" # noqa + + +def netcat_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"nc -z -w 1 {host} {port}" + + +def tcp_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", None, True) + host = get_key(config, "host", "127.0.0.1", False) + + return f"timeout 1 bash -c 'cat < /dev/null > /dev/tcp/{host}/{port}'" + + +def redis_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 6379, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"redis-cli -h {host} -p {port} -a $REDIS_PASSWORD ping | grep -q PONG" + + +def postgres_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 5432, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"pg_isready -h {host} -p {port} -U $POSTGRES_USER -d $POSTGRES_DB" + + +def mariadb_test(config: dict) -> str: + config = config or {} + port = get_key(config, "port", 3306, False) + host = get_key(config, "host", "127.0.0.1", False) + + return f"mariadb-admin --user=root --host={host} --port={port} --password=$MARIADB_ROOT_PASSWORD ping" diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/labels.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/labels.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/labels.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/labels.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/notes.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/notes.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/notes.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/notes.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/portal.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/portal.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/portal.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/portal.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/portals.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/portals.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/portals.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/portals.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/ports.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/ports.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/ports.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/ports.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/render.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/render.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/render.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/render.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/resources.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/resources.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/resources.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/resources.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/restart.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/restart.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/restart.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/restart.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/storage.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/storage.py new file mode 100644 index 0000000000..e697ba902a --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/storage.py @@ -0,0 +1,116 @@ +from typing import TYPE_CHECKING, TypedDict, Literal, NotRequired, Union + +if TYPE_CHECKING: + from render import Render + +try: + from .error import RenderError + from .validations import valid_fs_path_or_raise + from .volume_mount import VolumeMount +except ImportError: + from error import RenderError + from validations import valid_fs_path_or_raise + from volume_mount import VolumeMount + + +class IxStorageTmpfsConfig(TypedDict): + size: NotRequired[int] + mode: NotRequired[str] + + +class AclConfig(TypedDict, total=False): + path: str + + +class IxStorageHostPathConfig(TypedDict): + path: NotRequired[str] # Either this or acl.path must be set + acl_enable: NotRequired[bool] + acl: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageIxVolumeConfig(TypedDict): + dataset_name: str + acl_enable: NotRequired[bool] + acl_entries: NotRequired[AclConfig] + create_host_path: NotRequired[bool] + propagation: NotRequired[Literal["shared", "slave", "private", "rshared", "rslave", "rprivate"]] + auto_permissions: NotRequired[bool] # Only when acl_enable is false + + +class IxStorageVolumeConfig(TypedDict): + volume_name: NotRequired[str] + nocopy: NotRequired[bool] + auto_permissions: NotRequired[bool] + + +class IxStorageNfsConfig(TypedDict): + server: str + path: str + options: NotRequired[list[str]] + + +class IxStorageCifsConfig(TypedDict): + server: str + path: str + username: str + password: str + domain: NotRequired[str] + options: NotRequired[list[str]] + + +IxStorageVolumeLikeConfigs = Union[IxStorageVolumeConfig, IxStorageNfsConfig, IxStorageCifsConfig, IxStorageTmpfsConfig] +IxStorageBindLikeConfigs = Union[IxStorageHostPathConfig, IxStorageIxVolumeConfig] +IxStorageLikeConfigs = Union[IxStorageBindLikeConfigs, IxStorageVolumeLikeConfigs] + + +class IxStorage(TypedDict): + type: Literal["ix_volume", "host_path", "tmpfs", "volume", "anonymous", "temporary"] + read_only: NotRequired[bool] + + ix_volume_config: NotRequired[IxStorageIxVolumeConfig] + host_path_config: NotRequired[IxStorageHostPathConfig] + tmpfs_config: NotRequired[IxStorageTmpfsConfig] + volume_config: NotRequired[IxStorageVolumeConfig] + nfs_config: NotRequired[IxStorageNfsConfig] + cifs_config: NotRequired[IxStorageCifsConfig] + + +class Storage: + def __init__(self, render_instance: "Render"): + self._render_instance = render_instance + self._volume_mounts: set[VolumeMount] = set() + + def add(self, mount_path: str, config: "IxStorage"): + mount_path = valid_fs_path_or_raise(mount_path) + if mount_path in [m.mount_path for m in self._volume_mounts]: + raise RenderError(f"Mount path [{mount_path}] already used for another volume mount") + + volume_mount = VolumeMount(self._render_instance, mount_path, config) + self._volume_mounts.add(volume_mount) + + def _add_docker_socket(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/var/run/docker.sock", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def _add_tun_device(self, read_only: bool = True, mount_path: str = ""): + mount_path = valid_fs_path_or_raise(mount_path) + cfg: "IxStorage" = { + "type": "host_path", + "read_only": read_only, + "host_path_config": {"path": "/dev/net/tun", "create_host_path": False}, + } + self.add(mount_path, cfg) + + def has_mounts(self) -> bool: + return bool(self._volume_mounts) + + def render(self): + return [vm.render() for vm in sorted(self._volume_mounts, key=lambda vm: vm.mount_path)] diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/sysctls.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/sysctls.py new file mode 100644 index 0000000000..e6b8469f3b --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/sysctls.py @@ -0,0 +1,38 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from render import Render + from container import Container + +try: + from .error import RenderError + from .validations import valid_sysctl_or_raise +except ImportError: + from error import RenderError + from validations import valid_sysctl_or_raise + + +class Sysctls: + def __init__(self, render_instance: "Render", container_instance: "Container"): + self._render_instance = render_instance + self._container_instance = container_instance + self._sysctls: dict = {} + + def add(self, key: str, value): + key = key.strip() + if not key: + raise RenderError("Sysctls key cannot be empty") + if value is None: + raise RenderError(f"Sysctl [{key}] requires a value") + if key in self._sysctls: + raise RenderError(f"Sysctl [{key}] already added") + self._sysctls[key] = str(value) + + def has_sysctls(self): + return bool(self._sysctls) + + def render(self): + if not self.has_sysctls(): + return {} + host_net = self._container_instance._network_mode == "host" + return {valid_sysctl_or_raise(k, host_net): v for k, v in self._sysctls.items()} diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/__init__.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/__init__.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/__init__.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/__init__.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_build_image.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_build_image.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_build_image.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_build_image.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_configs.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_configs.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_configs.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_configs.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_container.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_container.py new file mode 100644 index 0000000000..747ad39357 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_container.py @@ -0,0 +1,360 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_empty_container_name(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container(" ", "test_image") + + +def test_resolve_image(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["image"] == "nginx:latest" + + +def test_missing_repo(mock_values): + mock_values["images"]["test_image"]["repository"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_missing_tag(mock_values): + mock_values["images"]["test_image"]["tag"] = "" + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "test_image") + + +def test_non_existing_image(mock_values): + render = Render(mock_values) + with pytest.raises(Exception): + render.add_container("test_container", "non_existing_image") + + +def test_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_pull_policy("always") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["pull_policy"] == "always" + + +def test_invalid_pull_policy(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.set_pull_policy("invalid_policy") + + +def test_clear_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.add_caps(["NET_ADMIN"]) + c1.clear_caps() + c1.healthcheck.disable() + output = render.render() + assert "cap_drop" not in output["services"]["test_container"] + assert "cap_add" not in output["services"]["test_container"] + + +def test_privileged(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_privileged(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["privileged"] is True + + +def test_tty(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_tty(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["tty"] is True + + +def test_init(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_init(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["init"] is True + + +def test_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_read_only(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["read_only"] is True + + +def test_stdin(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_stdin(True) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stdin_open"] is True + + +def test_hostname(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_hostname("test_hostname") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["hostname"] == "test_hostname" + + +def test_grace_period(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_grace_period(10) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["stop_grace_period"] == "10s" + + +def test_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_user(1000, 1000) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["user"] == "1000:1000" + + +def test_invalid_user(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_user(-100, 1000) + + +def test_add_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + c1.add_group("video") + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 1000, "video"] + + +def test_add_duplicate_group(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_group(1000) + with pytest.raises(Exception): + c1.add_group(1000) + + +def test_add_group_as_string(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_group("1000") + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_docker_socket() + output = render.render() + assert output["services"]["test_container"]["group_add"] == [568, 999] + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_tun_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_tun_device() + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/dev/net/tun", + "target": "/dev/net/tun", + "read_only": True, + "bind": { + "propagation": "rprivate", + "create_host_path": False, + }, + } + ] + + +def test_snd_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_snd_device() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/snd:/dev/snd"] + assert output["services"]["test_container"]["group_add"] == [29, 568] + + +def test_shm_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_shm_size_mb(10) + output = render.render() + assert output["services"]["test_container"]["shm_size"] == "10M" + + +def test_valid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_caps(["ALL", "NET_ADMIN"]) + output = render.render() + assert output["services"]["test_container"]["cap_add"] == ["ALL", "NET_ADMIN"] + assert output["services"]["test_container"]["cap_drop"] == ["ALL"] + + +def test_add_duplicate_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["ALL", "NET_ADMIN", "NET_ADMIN"]) + + +def test_invalid_caps(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_caps(["invalid_cap"]) + + +def test_remove_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.remove_security_opt("no-new-privileges") + output = render.render() + assert "security_opt" not in output["services"]["test_container"] + + +def test_add_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_security_opt("seccomp=unconfined") + output = render.render() + assert output["services"]["test_container"]["security_opt"] == [ + "no-new-privileges", + "seccomp=unconfined", + ] + + +def test_add_duplicate_security_opt(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_security_opt("no-new-privileges") + + +def test_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_auto_network_mode_with_host_network(mock_values): + mock_values["network"] = {"host_network": True} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "host" + + +def test_network_mode_with_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("service:test_container") + output = render.render() + assert output["services"]["test_container"]["network_mode"] == "service:test_container" + + +def test_network_mode_with_container_missing(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("service:missing_container") + + +def test_invalid_network_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.set_network_mode("invalid_mode") + + +def test_entrypoint(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_entrypoint(["/bin/bash", "-c", "echo hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["entrypoint"] == ["/bin/bash", "-c", "echo hello $$MY_ENV"] + + +def test_command(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.set_command(["echo", "hello $MY_ENV"]) + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["command"] == ["echo", "hello $$MY_ENV"] diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_depends.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_depends.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_depends.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_depends.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py new file mode 100644 index 0000000000..a1b7f03a60 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_deps.py @@ -0,0 +1,477 @@ +import json +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_postgres_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "16"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + p = render.deps.postgres( + "pg_container", + "pg_image", + { + "user": "test_user", + "password": "test_@password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + p.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert ( + p.get_url("postgres") == "postgres://test_user:test_%40password@pg_container:5432/test_database?sslmode=disable" + ) + assert "devices" not in output["services"]["pg_container"] + assert "reservations" not in output["services"]["pg_container"]["deploy"]["resources"] + assert output["services"]["pg_container"]["image"] == "postgres:16" + assert output["services"]["pg_container"]["user"] == "999:999" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["pg_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["pg_container"]["healthcheck"] == { + "test": "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["pg_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/postgresql/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["pg_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "POSTGRES_USER": "test_user", + "POSTGRES_PASSWORD": "test_@password", + "POSTGRES_DB": "test_database", + "POSTGRES_PORT": "5432", + } + assert output["services"]["pg_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"}, + "pg_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert output["services"]["perms_container"]["restart"] == "on-failure:1" + + +def test_add_redis_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test_password", "volume": {}}, # type: ignore + ) + + +def test_add_redis_with_password_with_spaces(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.redis( + "test_container", + "test_image", + {"password": "test password", "volume": {}}, # type: ignore + ) + + +def test_add_redis(mock_values): + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + r = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test&password@", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + c1.environment.add_env("REDIS_URL", r.get_url("redis")) + if perms_container.has_actions(): + perms_container.activate() + r.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["redis_container"] + assert "reservations" not in output["services"]["redis_container"]["deploy"]["resources"] + assert ( + output["services"]["test_container"]["environment"]["REDIS_URL"] + == "redis://default:test%26password%40@redis_container:6379" + ) + assert output["services"]["redis_container"]["image"] == "redis:latest" + assert output["services"]["redis_container"]["user"] == "1001:0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["redis_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["redis_container"]["healthcheck"] == { + "test": "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["redis_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/bitnami/redis/data", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["redis_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "ALLOW_EMPTY_PASSWORD": "no", + "REDIS_PASSWORD": "test&password@", + "REDIS_PORT_NUMBER": "6379", + } + assert output["services"]["redis_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_mariadb_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.mariadb( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_mariadb(mock_values): + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("perms_container") + m = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + m.container.depends.add_dependency("perms_container", "service_completed_successfully") + output = render.render() + assert "devices" not in output["services"]["mariadb_container"] + assert "reservations" not in output["services"]["mariadb_container"]["deploy"]["resources"] + assert output["services"]["mariadb_container"]["image"] == "mariadb:latest" + assert output["services"]["mariadb_container"]["user"] == "999:999" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["cpus"] == "2.0" + assert output["services"]["mariadb_container"]["deploy"]["resources"]["limits"]["memory"] == "4096M" + assert output["services"]["mariadb_container"]["healthcheck"] == { + "test": "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + assert output["services"]["mariadb_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/var/lib/mysql", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["services"]["mariadb_container"]["environment"] == { + "TZ": "Etc/UTC", + "UMASK": "002", + "UMASK_SET": "002", + "NVIDIA_VISIBLE_DEVICES": "void", + "MARIADB_USER": "test_user", + "MARIADB_PASSWORD": "test_password", + "MARIADB_ROOT_PASSWORD": "test_password", + "MARIADB_DATABASE": "test_database", + "MARIADB_AUTO_UPGRADE": "true", + } + assert output["services"]["mariadb_container"]["depends_on"] == { + "perms_container": {"condition": "service_completed_successfully"} + } + + +def test_add_perms_container(mock_values): + mock_values["ix_volumes"] = { + "test_dataset1": "/mnt/test/1", + "test_dataset2": "/mnt/test/2", + "test_dataset3": "/mnt/test/3", + } + mock_values["images"]["postgres_image"] = {"repository": "postgres", "tag": "17"} + mock_values["images"]["redis_image"] = {"repository": "redis", "tag": "latest"} + mock_values["images"]["mariadb_image"] = {"repository": "mariadb", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + # fmt: off + volume_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + volume_no_perms = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + host_path_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "auto_permissions": True}} + host_path_no_perms = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + host_path_acl_perms = {"type": "host_path", "host_path_config": {"acl": {"path": "/mnt/test"}, "acl_enable": True, "auto_permissions": True}} # noqa + ix_volume_no_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset1"}} + ix_volume_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset2", "auto_permissions": True}} # noqa + ix_volume_acl_perms = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset3", "acl_enable": True, "auto_permissions": True}} # noqa + temp_volume = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + # fmt: on + + c1.add_storage("/some/path1", volume_perms) + c1.add_storage("/some/path2", volume_no_perms) + c1.add_storage("/some/path3", host_path_perms) + c1.add_storage("/some/path4", host_path_no_perms) + c1.add_storage("/some/path5", host_path_acl_perms) + c1.add_storage("/some/path6", ix_volume_no_perms) + c1.add_storage("/some/path7", ix_volume_perms) + c1.add_storage("/some/path8", ix_volume_acl_perms) + c1.add_storage("/some/path9", temp_volume) + + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data2", volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data3", host_path_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data4", host_path_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data5", host_path_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data6", ix_volume_no_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data7", ix_volume_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data8", ix_volume_acl_perms, {"uid": 1000, "gid": 1000, "mode": "check"}) + perms_container.add_or_skip_action("data9", temp_volume, {"uid": 1000, "gid": 1000, "mode": "check"}) + + postgres = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + redis = render.deps.redis( + "redis_container", + "redis_image", + { + "password": "test_password", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + mariadb = render.deps.mariadb( + "mariadb_container", + "mariadb_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + postgres.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + redis.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + mariadb.container.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert output["services"]["test_perms_container"]["network_mode"] == "none" + assert output["services"]["test_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + assert output["configs"]["permissions_run_script"]["content"] != "" + # fmt: off + content = [ + {"mount_path": "/mnt/permission/data", "is_temporary": False, "identifier": "data", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data3", "is_temporary": False, "identifier": "data3", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data6", "is_temporary": False, "identifier": "data6", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data7", "is_temporary": False, "identifier": "data7", "recursive": False, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/data9", "is_temporary": True, "identifier": "data9", "recursive": True, "mode": "check", "uid": 1000, "gid": 1000, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/postgres_container_postgres_data", "is_temporary": False, "identifier": "postgres_container_postgres_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/redis_container_redis_data", "is_temporary": False, "identifier": "redis_container_redis_data", "recursive": False, "mode": "check", "uid": 1001, "gid": 0, "chmod": None}, # noqa + {"mount_path": "/mnt/permission/mariadb_container_mariadb_data", "is_temporary": False, "identifier": "mariadb_container_mariadb_data", "recursive": False, "mode": "check", "uid": 999, "gid": 999, "chmod": None}, # noqa + ] + # fmt: on + assert output["configs"]["permissions_actions_data"]["content"] == json.dumps(content) + + +def test_add_duplicate_perms_action(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + with pytest.raises(Exception): + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + + +def test_add_perm_action_without_auto_perms_enabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": False}} + c1.add_storage("/some/path", vol_config) + perms_container = render.deps.perms("test_perms_container") + perms_container.add_or_skip_action("data", vol_config, {"uid": 1000, "gid": 1000, "mode": "check"}) + if perms_container.has_actions(): + perms_container.activate() + c1.depends.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert "configs" not in output + assert "ix-test_perms_container" not in output["services"] + assert "depends_on" not in output["services"]["test_container"] + + +def test_add_unsupported_postgres_version(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "99"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_add_postgres_with_invalid_tag(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": "latest"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + render.deps.postgres( + "test_container", + "test_image", + {"user": "test_user", "password": "test_password", "database": "test_database"}, # type: ignore + ) + + +def test_no_upgrade_container_with_non_postgres_image(mock_values): + mock_values["images"]["postgres_image"] = {"repository": "tensorchord/pgvecto-rs", "tag": "pg15-v0.2.0"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "postgres_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + assert len(output["services"]) == 3 # c1, pg, perms + assert output["services"]["postgres_container"]["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"} + } + + +def test_postgres_with_upgrade_container(mock_values): + mock_values["images"]["pg_image"] = {"repository": "postgres", "tag": 16.6} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + perms_container = render.deps.perms("test_perms_container") + pg = render.deps.postgres( + "postgres_container", + "pg_image", + { + "user": "test_user", + "password": "test_password", + "database": "test_database", + "volume": {"type": "volume", "volume_config": {"volume_name": "test_volume", "auto_permissions": True}}, + }, + perms_container, + ) + if perms_container.has_actions(): + perms_container.activate() + pg.add_dependency("test_perms_container", "service_completed_successfully") + output = render.render() + pg = output["services"]["postgres_container"] + pgup = output["services"]["postgres_container_upgrade"] + assert pg["volumes"] == pgup["volumes"] + assert pg["user"] == pgup["user"] + assert pgup["environment"]["TARGET_VERSION"] == "16" + assert pgup["environment"]["DATA_DIR"] == "/var/lib/postgresql/data" + pgup_env = pgup["environment"] + pgup_env.pop("TARGET_VERSION") + pgup_env.pop("DATA_DIR") + assert pg["environment"] == pgup_env + assert pg["depends_on"] == { + "test_perms_container": {"condition": "service_completed_successfully"}, + "postgres_container_upgrade": {"condition": "service_completed_successfully"}, + } + assert pgup["depends_on"] == {"test_perms_container": {"condition": "service_completed_successfully"}} + assert pgup["restart"] == "on-failure:1" + assert pgup["healthcheck"] == {"disable": True} + assert pgup["build"]["dockerfile_inline"] != "" + assert pgup["configs"][0]["source"] == "pg_container_upgrade.sh" + assert pgup["entrypoint"] == ["/bin/bash", "-c", "/upgrade.sh"] diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_device.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_device.py new file mode 100644 index 0000000000..c44437367d --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_device.py @@ -0,0 +1,131 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + c1.devices.add_device("/h/dev/sdb", "/c/dev/sdb", "rwm") + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/h/dev/sda:/c/dev/sda", "/h/dev/sdb:/c/dev/sdb:rwm"] + + +def test_devices_without_host(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("", "/c/dev/sda") + + +def test_devices_without_container(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "") + + +def test_add_duplicate_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda") + + +def test_add_device_with_invalid_container_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "c/dev/sda") + + +def test_add_device_with_invalid_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("h/dev/sda", "/c/dev/sda") + + +def test_add_disallowed_device(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/dri", "/c/dev/sda") + + +def test_add_device_with_invalid_cgroup_perm(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/h/dev/sda", "/c/dev/sda", "invalid") + + +def test_automatically_add_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_automatically_add_gpu_devices_and_kfd(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True, "kfd_device_exists": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/dri:/dev/dri", "/dev/kfd:/dev/kfd"] + assert output["services"]["test_container"]["group_add"] == [44, 107, 568] + + +def test_remove_gpu_devices(mock_values): + mock_values["resources"] = {"gpus": {"use_all_gpus": True}} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.remove_devices() + output = render.render() + assert "devices" not in output["services"]["test_container"] + assert output["services"]["test_container"]["group_add"] == [568] + + +def test_add_usb_bus(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.devices.add_usb_bus() + output = render.render() + assert output["services"]["test_container"]["devices"] == ["/dev/bus/usb:/dev/bus/usb"] + + +def test_add_usb_bus_disallowed(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.devices.add_device("/dev/bus/usb", "/dev/bus/usb") diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_dns.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_dns.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_dns.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_dns.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py new file mode 100644 index 0000000000..d657646582 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_environment.py @@ -0,0 +1,196 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_auto_add_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + mock_values["run_as"] = {"user": "1000", "group": "1000"} + mock_values["resources"] = { + "gpus": { + "nvidia_gpu_selection": { + "pci_slot_0": {"uuid": "uuid_0", "use_gpu": True}, + "pci_slot_1": {"uuid": "uuid_1", "use_gpu": True}, + }, + } + } + + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert len(envs) == 11 + assert envs["TZ"] == "Etc/UTC" + assert envs["PUID"] == "1000" + assert envs["UID"] == "1000" + assert envs["USER_ID"] == "1000" + assert envs["PGID"] == "1000" + assert envs["GID"] == "1000" + assert envs["GROUP_ID"] == "1000" + assert envs["UMASK"] == "002" + assert envs["UMASK_SET"] == "002" + assert envs["NVIDIA_DRIVER_CAPABILITIES"] == "all" + assert envs["NVIDIA_VISIBLE_DEVICES"] == "uuid_0,uuid_1" + + +def test_skip_generic_variables(mock_values): + mock_values["skip_generic_variables"] = True + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + envs = output["services"]["test_container"]["environment"] + + assert len(envs) == 1 + assert envs["NVIDIA_VISIBLE_DEVICES"] == "void" + + +def test_add_from_all_sources(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_value") + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_value" + assert envs["USER_ENV"] == "test_value2" + assert envs["TZ"] == "Etc/UTC" + + +def test_user_add_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV2", "value": "test_value2"}, + ] + ) + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["MY_ENV"] == "test_value" + assert envs["MY_ENV2"] == "test_value2" + + +def test_user_add_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "MY_ENV", "value": "test_value"}, + {"name": "MY_ENV", "value": "test_value2"}, + ] + ) + + +def test_user_env_without_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_user_envs( + [ + {"name": "", "value": "test_value"}, + ] + ) + + +def test_user_env_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "TZ", "value": "test_value"}, + ] + ) + with pytest.raises(Exception): + render.render() + + +def test_user_env_try_to_overwrite_app_dev_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_user_envs( + [ + {"name": "PORT", "value": "test_value"}, + ] + ) + c1.environment.add_env("PORT", "test_value2") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_vars_try_to_overwrite_auto_vars(mock_values): + mock_values["TZ"] = "Etc/UTC" + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("TZ", "test_value") + with pytest.raises(Exception): + render.render() + + +def test_app_dev_no_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.environment.add_env("", "test_value") + + +def test_app_dev_duplicate_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("PORT", "test_value") + with pytest.raises(Exception): + c1.environment.add_env("PORT", "test_value2") + + +def test_format_vars(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.environment.add_env("APP_ENV", "test_$value") + c1.environment.add_env("APP_ENV_BOOL", True) + c1.environment.add_env("APP_ENV_INT", 10) + c1.environment.add_env("APP_ENV_FLOAT", 10.5) + c1.environment.add_user_envs( + [ + {"name": "USER_ENV", "value": "test_$value2"}, + ] + ) + + output = render.render() + envs = output["services"]["test_container"]["environment"] + assert envs["APP_ENV"] == "test_$$value" + assert envs["USER_ENV"] == "test_$$value2" + assert envs["APP_ENV_BOOL"] == "true" + assert envs["APP_ENV_INT"] == "10" + assert envs["APP_ENV_FLOAT"] == "10.5" diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_formatter.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_formatter.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_formatter.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_formatter.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_functions.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_functions.py new file mode 100644 index 0000000000..0ea3b57d18 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_functions.py @@ -0,0 +1,88 @@ +import re +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_funcs(mock_values): + mock_values["ix_volumes"] = {"test": "/mnt/test123"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + + tests = [ + {"func": "auto_cast", "values": ["1"], "expected": 1}, + {"func": "basic_auth_header", "values": ["my_user", "my_pass"], "expected": "Basic bXlfdXNlcjpteV9wYXNz"}, + {"func": "basic_auth", "values": ["my_user", "my_pass"], "expected": "bXlfdXNlcjpteV9wYXNz"}, + { + "func": "bcrypt_hash", + "values": ["my_pass"], + "expect_regex": r"^\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "camel_case", "values": ["my_user"], "expected": "My_User"}, + {"func": "copy_dict", "values": [{"a": 1}], "expected": {"a": 1}}, + {"func": "fail", "values": ["my_message"], "expect_raise": True}, + { + "func": "htpasswd", + "values": ["my_user", "my_pass"], + "expect_regex": r"^my_user:\$2b\$12\$[a-zA-Z0-9-_\.\/]+$", + }, + {"func": "is_boolean", "values": ["true"], "expected": True}, + {"func": "is_boolean", "values": ["false"], "expected": True}, + {"func": "is_number", "values": ["1"], "expected": True}, + {"func": "is_number", "values": ["1.1"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[a-zA-Z0-9]+$"], "expected": True}, + {"func": "match_regex", "values": ["value", "^[0-9]+$"], "expected": False}, + {"func": "merge_dicts", "values": [{"a": 1}, {"b": 2}], "expected": {"a": 1, "b": 2}}, + {"func": "must_match_regex", "values": ["my_user", "^[0-9]$"], "expect_raise": True}, + {"func": "must_match_regex", "values": ["1", "^[0-9]$"], "expected": "1"}, + {"func": "secure_string", "values": [10], "expect_regex": r"^[a-zA-Z0-9-_]+$"}, + {"func": "disallow_chars", "values": ["my_user", ["$", "@"], "my_key"], "expected": "my_user"}, + {"func": "disallow_chars", "values": ["my_user$", ["$", "@"], "my_key"], "expect_raise": True}, + { + "func": "get_host_path", + "values": [{"type": "host_path", "host_path_config": {"path": "/mnt/test"}}], + "expected": "/mnt/test", + }, + { + "func": "get_host_path", + "values": [{"type": "ix_volume", "ix_volume_config": {"dataset_name": "test"}}], + "expected": "/mnt/test123", + }, + {"func": "or_default", "values": [None, 1], "expected": 1}, + {"func": "or_default", "values": [1, None], "expected": 1}, + {"func": "or_default", "values": [False, 1], "expected": 1}, + {"func": "or_default", "values": [True, 1], "expected": True}, + {"func": "temp_config", "values": [""], "expect_raise": True}, + { + "func": "temp_config", + "values": ["test"], + "expected": {"type": "temporary", "volume_config": {"volume_name": "test"}}, + }, + ] + + for test in tests: + print(test["func"], test) + func = render.funcs[test["func"]] + if test.get("expect_raise", False): + with pytest.raises(Exception): + func(*test["values"]) + elif test.get("expect_regex"): + r = func(*test["values"]) + assert re.match(test["expect_regex"], r) is not None + else: + r = func(*test["values"]) + assert r == test["expected"] diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py new file mode 100644 index 0000000000..8fa044290f --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_healthcheck.py @@ -0,0 +1,195 @@ +import pytest + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_disable_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == {"disable": True} + + +def test_use_built_in_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.use_built_in() + output = render.render() + assert "healthcheck" not in output["services"]["test_container"] + + +def test_set_custom_test(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test("echo $1") + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": "echo $$1", + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_custom_test_array(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "10s", + "timeout": "5s", + "retries": 30, + "start_period": "10s", + } + + +def test_set_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_custom_test(["CMD", "echo", "$1"]) + c1.healthcheck.set_interval(9) + c1.healthcheck.set_timeout(8) + c1.healthcheck.set_retries(7) + c1.healthcheck.set_start_period(6) + output = render.render() + assert output["services"]["test_container"]["healthcheck"] == { + "test": ["CMD", "echo", "$$1"], + "interval": "9s", + "timeout": "8s", + "retries": 7, + "start_period": "6s", + } + + +def test_adding_test_when_disabled(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.healthcheck.set_custom_test("echo $1") + + +def test_not_adding_test(mock_values): + render = Render(mock_values) + render.add_container("test_container", "test_image") + with pytest.raises(Exception): + render.render() + + +def test_invalid_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + with pytest.raises(Exception): + c1.healthcheck.set_test("http", {"port": 8080, "path": "invalid"}) + + +def test_http_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("http", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == """/bin/bash -c 'exec {hc_fd}<>/dev/tcp/127.0.0.1/8080 && echo -e "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nConnection: close\\r\\n\\r\\n" >&$${hc_fd} && cat <&$${hc_fd} | grep "HTTP" | grep -q "200"'""" # noqa + ) + + +def test_curl_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "curl --silent --output /dev/null --show-error --fail http://127.0.0.1:8080/health" + ) + + +def test_curl_healthcheck_with_headers(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("curl", {"port": 8080, "path": "/health", "headers": [("X-Test", "$test")]}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == 'curl --silent --output /dev/null --show-error --fail --header "X-Test: $$test" http://127.0.0.1:8080/health' + ) + + +def test_wget_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("wget", {"port": 8080, "path": "/health"}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "wget --spider --quiet http://127.0.0.1:8080/health" + ) + + +def test_netcat_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("netcat", {"port": 8080}) + output = render.render() + assert output["services"]["test_container"]["healthcheck"]["test"] == "nc -z -w 1 127.0.0.1 8080" + + +def test_tcp_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("tcp", {"port": 8080}) + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/8080'" + ) + + +def test_redis_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("redis") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "redis-cli -h 127.0.0.1 -p 6379 -a $$REDIS_PASSWORD ping | grep -q PONG" + ) + + +def test_postgres_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("postgres") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "pg_isready -h 127.0.0.1 -p 5432 -U $$POSTGRES_USER -d $$POSTGRES_DB" + ) + + +def test_mariadb_healthcheck(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.set_test("mariadb") + output = render.render() + assert ( + output["services"]["test_container"]["healthcheck"]["test"] + == "mariadb-admin --user=root --host=127.0.0.1 --port=3306 --password=$$MARIADB_ROOT_PASSWORD ping" + ) diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_labels.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_labels.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_labels.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_labels.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_notes.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_notes.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_notes.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_notes.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_portal.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_portal.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_portal.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_portal.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_ports.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_ports.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_ports.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_ports.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_render.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_render.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_render.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_render.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_resources.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_resources.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_resources.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_resources.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_restart.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_restart.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/tests/test_restart.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_restart.py diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_sysctls.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_sysctls.py new file mode 100644 index 0000000000..c9414044ea --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_sysctls.py @@ -0,0 +1,62 @@ +import pytest + + +from render import Render + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + c1.sysctls.add("fs.mqueue.msg_max", 100) + output = render.render() + assert output["services"]["test_container"]["sysctls"] == {"net.ipv4.ip_forward": "1", "fs.mqueue.msg_max": "100"} + + +def test_add_net_sysctl_with_host_network(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.set_network_mode("host") + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + render.render() + + +def test_add_duplicate_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("net.ipv4.ip_forward", 1) + with pytest.raises(Exception): + c1.sysctls.add("net.ipv4.ip_forward", 0) + + +def test_add_empty_sysctl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.sysctls.add("", 1) + + +def test_add_sysctl_with_invalid_key(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.sysctls.add("invalid.sysctl", 1) + with pytest.raises(Exception): + render.render() diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_volumes.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_volumes.py new file mode 100644 index 0000000000..aef0d39481 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/tests/test_volumes.py @@ -0,0 +1,666 @@ +import pytest + + +from render import Render +from formatter import get_hashed_name_for_volume + + +@pytest.fixture +def mock_values(): + return { + "images": { + "test_image": { + "repository": "nginx", + "tag": "latest", + } + }, + } + + +def test_add_volume_invalid_type(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "invalid_type"}) + + +def test_add_volume_empty_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + with pytest.raises(Exception): + c1.add_storage("", {"type": "tmpfs"}) + + +def test_add_volume_duplicate_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.add_storage("/some/path", {"type": "tmpfs"}) + with pytest.raises(Exception): + c1.add_storage("/some/path", {"type": "tmpfs"}) + + +def test_add_volume_host_path_invalid_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "propagation": "invalid_propagation"}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_host_path_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path"} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_with_acl_no_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"acl_enable": True, "acl": {"path": ""}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", host_path_config) + + +def test_add_host_path_volume_mount(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_acl(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = { + "type": "host_path", + "host_path_config": {"path": "/mnt/test", "acl_enable": True, "acl": {"path": "/mnt/test/acl"}}, + } + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test/acl", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_propagation(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "propagation": "slave"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "slave"}, + } + ] + + +def test_add_host_path_volume_mount_with_create_host_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "host_path_config": {"path": "/mnt/test", "create_host_path": True}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rprivate"}, + } + ] + + +def test_add_host_path_volume_mount_with_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + host_path_config = {"type": "host_path", "read_only": True, "host_path_config": {"path": "/mnt/test"}} + c1.add_storage("/some/path", host_path_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_invalid_dataset_name(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "invalid_dataset"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_no_ix_volume_config(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume"} + with pytest.raises(Exception): + c1.add_storage("/some/path", ix_volume_config) + + +def test_add_ix_volume_volume_mount(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = {"type": "ix_volume", "ix_volume_config": {"dataset_name": "test_dataset"}} + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_ix_volume_volume_mount_with_options(mock_values): + mock_values["ix_volumes"] = {"test_dataset": "/mnt/test"} + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + ix_volume_config = { + "type": "ix_volume", + "ix_volume_config": {"dataset_name": "test_dataset", "propagation": "rslave", "create_host_path": True}, + } + c1.add_storage("/some/path", ix_volume_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/mnt/test", + "target": "/some/path", + "read_only": False, + "bind": {"create_host_path": True, "propagation": "rslave"}, + } + ] + + +def test_cifs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"path": "/path", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "username": "user", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_username(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "password": "password"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_missing_password(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs", "cifs_config": {"server": "server", "path": "/path", "username": "user"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_without_cifs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = {"type": "cifs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["verbose=true", "verbose=true"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["user=username"], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": {"verbose": True}, + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_cifs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_config = { + "type": "cifs", + "cifs_config": { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": [{"verbose": True}], + }, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", cifs_config) + + +def test_add_cifs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = {"server": "server", "path": "/path", "username": "user", "password": "pas$word"} + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": {"type": "cifs", "device": "//server/path", "o": "noperm,password=pas$$word,user=user"} + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_cifs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + cifs_inner_config = { + "server": "server", + "path": "/path", + "username": "user", + "password": "pas$word", + "options": ["vers=3.0", "verbose=true"], + } + cifs_config = {"type": "cifs", "cifs_config": cifs_inner_config} + c1.add_storage("/some/path", cifs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("cifs", cifs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "cifs", + "device": "//server/path", + "o": "noperm,password=pas$$word,user=user,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_missing_server(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"path": "/path"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_missing_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_without_nfs_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs"} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_duplicate_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = { + "type": "nfs", + "nfs_config": {"server": "server", "path": "/path", "options": ["verbose=true", "verbose=true"]}, + } + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_disallowed_option(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": ["addr=server"]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": {"verbose": True}}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_nfs_volume_invalid_options2(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_config = {"type": "nfs", "nfs_config": {"server": "server", "path": "/path", "options": [{"verbose": True}]}} + with pytest.raises(Exception): + c1.add_storage("/some/path", nfs_config) + + +def test_add_nfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path"} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == {vol_name: {"driver_opts": {"type": "nfs", "device": ":/path", "o": "addr=server"}}} + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_nfs_volume_with_options(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + nfs_inner_config = {"server": "server", "path": "/path", "options": ["vers=3.0", "verbose=true"]} + nfs_config = {"type": "nfs", "nfs_config": nfs_inner_config} + c1.add_storage("/some/path", nfs_config) + output = render.render() + vol_name = get_hashed_name_for_volume("nfs", nfs_inner_config) + assert output["volumes"] == { + vol_name: { + "driver_opts": { + "type": "nfs", + "device": ":/path", + "o": "addr=server,verbose=true,vers=3.0", + } + } + } + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "source": vol_name, "target": "/some/path", "read_only": False, "volume": {"nocopy": False}} + ] + + +def test_tmpfs_invalid_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": "2"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_zero_size(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"size": 0}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_invalid_mode(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs", "tmpfs_config": {"mode": "invalid"}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_tmpfs_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "tmpfs"} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "tmpfs", + "target": "/some/path", + "read_only": False, + } + ] + + +def test_temporary_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "temporary", "volume_config": {"volume_name": "test_temp_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "source": "test_temp_volume", + "type": "volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + + +def test_docker_volume_missing_config(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume_missing_volume_name(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": ""}} + with pytest.raises(Exception): + c1.add_storage("/some/path", vol_config) + + +def test_docker_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "volume", "volume_config": {"volume_name": "test_volume"}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "volume", + "source": "test_volume", + "target": "/some/path", + "read_only": False, + "volume": {"nocopy": False}, + } + ] + assert output["volumes"] == {"test_volume": {}} + + +def test_anonymous_volume(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + vol_config = {"type": "anonymous", "volume_config": {"nocopy": True}} + c1.add_storage("/some/path", vol_config) + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + {"type": "volume", "target": "/some/path", "read_only": False, "volume": {"nocopy": True}} + ] + assert "volumes" not in output + + +def test_add_docker_socket(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_not_read_only(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(read_only=False, mount_path="/var/run/docker.sock") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/var/run/docker.sock", + "read_only": False, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] + + +def test_add_docker_socket_mount_path(mock_values): + render = Render(mock_values) + c1 = render.add_container("test_container", "test_image") + c1.healthcheck.disable() + c1.storage._add_docker_socket(mount_path="/some/path") + output = render.render() + assert output["services"]["test_container"]["volumes"] == [ + { + "type": "bind", + "source": "/var/run/docker.sock", + "target": "/some/path", + "read_only": True, + "bind": {"create_host_path": False, "propagation": "rprivate"}, + } + ] diff --git a/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/validations.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/validations.py new file mode 100644 index 0000000000..43dd96b475 --- /dev/null +++ b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/validations.py @@ -0,0 +1,234 @@ +import re +import ipaddress + +try: + from .error import RenderError +except ImportError: + from error import RenderError + +OCTAL_MODE_REGEX = re.compile(r"^0[0-7]{3}$") + + +def valid_pull_policy_or_raise(pull_policy: str): + valid_policies = ("missing", "always", "never", "build") + if pull_policy not in valid_policies: + raise RenderError(f"Pull policy [{pull_policy}] is not valid. Valid options are: [{', '.join(valid_policies)}]") + return pull_policy + + +def valid_sysctl_or_raise(sysctl: str, host_network: bool): + if not sysctl: + raise RenderError("Sysctl cannot be empty") + if host_network and sysctl.startswith("net."): + raise RenderError(f"Sysctl [{sysctl}] cannot start with [net.] when host network is enabled") + + valid_sysctls = [ + "kernel.msgmax", + "kernel.msgmnb", + "kernel.msgmni", + "kernel.sem", + "kernel.shmall", + "kernel.shmmax", + "kernel.shmmni", + "kernel.shm_rmid_forced", + ] + # https://docs.docker.com/reference/cli/docker/container/run/#currently-supported-sysctls + if not sysctl.startswith("fs.mqueue.") and not sysctl.startswith("net.") and sysctl not in valid_sysctls: + raise RenderError( + f"Sysctl [{sysctl}] is not valid. Valid options are: [{', '.join(valid_sysctls)}], [net.*], [fs.mqueue.*]" + ) + return sysctl + + +def valid_redis_password_or_raise(password: str): + forbidden_chars = [" ", "'"] + for char in forbidden_chars: + if char in password: + raise RenderError(f"Redis password cannot contain [{char}]") + + +def valid_octal_mode_or_raise(mode: str): + mode = str(mode) + if not OCTAL_MODE_REGEX.match(mode): + raise RenderError(f"Expected [mode] to be a octal string, got [{mode}]") + return mode + + +def valid_host_path_propagation(propagation: str): + valid_propagations = ("shared", "slave", "private", "rshared", "rslave", "rprivate") + if propagation not in valid_propagations: + raise RenderError(f"Expected [propagation] to be one of [{', '.join(valid_propagations)}], got [{propagation}]") + return propagation + + +def valid_portal_scheme_or_raise(scheme: str): + schemes = ("http", "https") + if scheme not in schemes: + raise RenderError(f"Portal Scheme [{scheme}] is not valid. Valid options are: [{', '.join(schemes)}]") + return scheme + + +def valid_port_or_raise(port: int): + if port < 1 or port > 65535: + raise RenderError(f"Invalid port [{port}]. Valid ports are between 1 and 65535") + return port + + +def valid_ip_or_raise(ip: str): + try: + ipaddress.ip_address(ip) + except ValueError: + raise RenderError(f"Invalid IP address [{ip}]") + return ip + + +def valid_port_mode_or_raise(mode: str): + modes = ("ingress", "host") + if mode not in modes: + raise RenderError(f"Port Mode [{mode}] is not valid. Valid options are: [{', '.join(modes)}]") + return mode + + +def valid_port_protocol_or_raise(protocol: str): + protocols = ("tcp", "udp") + if protocol not in protocols: + raise RenderError(f"Port Protocol [{protocol}] is not valid. Valid options are: [{', '.join(protocols)}]") + return protocol + + +def valid_depend_condition_or_raise(condition: str): + valid_conditions = ("service_started", "service_healthy", "service_completed_successfully") + if condition not in valid_conditions: + raise RenderError( + f"Depend Condition [{condition}] is not valid. Valid options are: [{', '.join(valid_conditions)}]" + ) + return condition + + +def valid_cgroup_perm_or_raise(cgroup_perm: str): + valid_cgroup_perms = ("r", "w", "m", "rw", "rm", "wm", "rwm", "") + if cgroup_perm not in valid_cgroup_perms: + raise RenderError( + f"Cgroup Permission [{cgroup_perm}] is not valid. Valid options are: [{', '.join(valid_cgroup_perms)}]" + ) + return cgroup_perm + + +def allowed_dns_opt_or_raise(dns_opt: str): + disallowed_dns_opts = [] + if dns_opt in disallowed_dns_opts: + raise RenderError(f"DNS Option [{dns_opt}] is not allowed to added.") + return dns_opt + + +def valid_http_path_or_raise(path: str): + path = _valid_path_or_raise(path) + return path + + +def valid_fs_path_or_raise(path: str): + # There is no reason to allow / as a path, + # either on host or in a container side. + if path == "/": + raise RenderError(f"Path [{path}] cannot be [/]") + path = _valid_path_or_raise(path) + return path + + +def _valid_path_or_raise(path: str): + if path == "": + raise RenderError(f"Path [{path}] cannot be empty") + if not path.startswith("/"): + raise RenderError(f"Path [{path}] must start with /") + if "//" in path: + raise RenderError(f"Path [{path}] cannot contain [//]") + return path + + +def allowed_device_or_raise(path: str): + disallowed_devices = ["/dev/dri", "/dev/kfd", "/dev/bus/usb", "/dev/snd"] + if path in disallowed_devices: + raise RenderError(f"Device [{path}] is not allowed to be manually added.") + return path + + +def valid_network_mode_or_raise(mode: str, containers: list[str]): + valid_modes = ("host", "none") + if mode in valid_modes: + return mode + + if mode.startswith("service:"): + if mode[8:] not in containers: + raise RenderError(f"Service [{mode[8:]}] not found") + return mode + + raise RenderError( + f"Invalid network mode [{mode}]. Valid options are: [{', '.join(valid_modes)}] or [service:]" + ) + + +def valid_restart_policy_or_raise(policy: str, maximum_retry_count: int = 0): + valid_restart_policies = ("always", "on-failure", "unless-stopped", "no") + if policy not in valid_restart_policies: + raise RenderError( + f"Restart policy [{policy}] is not valid. Valid options are: [{', '.join(valid_restart_policies)}]" + ) + if policy != "on-failure" and maximum_retry_count != 0: + raise RenderError("Maximum retry count can only be set for [on-failure] restart policy") + + if maximum_retry_count < 0: + raise RenderError("Maximum retry count must be a positive integer") + + return policy + + +def valid_cap_or_raise(cap: str): + valid_policies = ( + "ALL", + "AUDIT_CONTROL", + "AUDIT_READ", + "AUDIT_WRITE", + "BLOCK_SUSPEND", + "BPF", + "CHECKPOINT_RESTORE", + "CHOWN", + "DAC_OVERRIDE", + "DAC_READ_SEARCH", + "FOWNER", + "FSETID", + "IPC_LOCK", + "IPC_OWNER", + "KILL", + "LEASE", + "LINUX_IMMUTABLE", + "MAC_ADMIN", + "MAC_OVERRIDE", + "MKNOD", + "NET_ADMIN", + "NET_BIND_SERVICE", + "NET_BROADCAST", + "NET_RAW", + "PERFMON", + "SETFCAP", + "SETGID", + "SETPCAP", + "SETUID", + "SYS_ADMIN", + "SYS_BOOT", + "SYS_CHROOT", + "SYS_MODULE", + "SYS_NICE", + "SYS_PACCT", + "SYS_PTRACE", + "SYS_RAWIO", + "SYS_RESOURCE", + "SYS_TIME", + "SYS_TTY_CONFIG", + "SYSLOG", + "WAKE_ALARM", + ) + + if cap not in valid_policies: + raise RenderError(f"Capability [{cap}] is not valid. " f"Valid options are: [{', '.join(valid_policies)}]") + + return cap diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_mount.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_mount.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_mount.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_mount.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_mount_types.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_mount_types.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_mount_types.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_mount_types.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_sources.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_sources.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_sources.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_sources.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_types.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_types.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volume_types.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volume_types.py diff --git a/trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volumes.py b/trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volumes.py similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/library/base_v2_0_32/volumes.py rename to trains/stable/wg-easy/1.1.2/templates/library/base_v2_1_0/volumes.py diff --git a/trains/stable/wg-easy/1.1.1/templates/test_values/basic-values.yaml b/trains/stable/wg-easy/1.1.2/templates/test_values/basic-values.yaml similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/test_values/basic-values.yaml rename to trains/stable/wg-easy/1.1.2/templates/test_values/basic-values.yaml diff --git a/trains/stable/wg-easy/1.1.1/templates/test_values/hostnet-values.yaml b/trains/stable/wg-easy/1.1.2/templates/test_values/hostnet-values.yaml similarity index 100% rename from trains/stable/wg-easy/1.1.1/templates/test_values/hostnet-values.yaml rename to trains/stable/wg-easy/1.1.2/templates/test_values/hostnet-values.yaml From 5d4c17f5d3568fbbf786d6d170c573d8786d1227 Mon Sep 17 00:00:00 2001 From: sonicaj Date: Fri, 6 Dec 2024 15:13:13 +0000 Subject: [PATCH 3/3] Update catalog changes [skip ci] --- catalog.json | 332 +++++++++--------- .../community/actual-budget/app_versions.json | 2 +- .../community/adguard-home/app_versions.json | 2 +- .../audiobookshelf/app_versions.json | 2 +- trains/community/autobrr/app_versions.json | 2 +- trains/community/bazarr/app_versions.json | 2 +- .../community/briefkasten/app_versions.json | 2 +- .../community/calibre-web/app_versions.json | 2 +- trains/community/calibre/app_versions.json | 2 +- trains/community/castopod/app_versions.json | 2 +- trains/community/chia/app_versions.json | 2 +- trains/community/clamav/app_versions.json | 2 +- .../community/cloudflared/app_versions.json | 2 +- trains/community/dashy/app_versions.json | 2 +- .../community/ddns-updater/app_versions.json | 2 +- trains/community/deluge/app_versions.json | 2 +- .../community/distribution/app_versions.json | 2 +- trains/community/dockge/app_versions.json | 2 +- trains/community/drawio/app_versions.json | 2 +- .../eclipse-mosquitto/app_versions.json | 2 +- .../community/filebrowser/app_versions.json | 2 +- trains/community/filestash/app_versions.json | 2 +- .../community/firefly-iii/app_versions.json | 2 +- trains/community/flame/app_versions.json | 2 +- .../community/flaresolverr/app_versions.json | 2 +- trains/community/freshrss/app_versions.json | 2 +- trains/community/frigate/app_versions.json | 2 +- trains/community/fscrawler/app_versions.json | 2 +- .../gaseous-server/app_versions.json | 2 +- trains/community/gitea/app_versions.json | 2 +- trains/community/grafana/app_versions.json | 2 +- trains/community/handbrake/app_versions.json | 2 +- trains/community/homarr/app_versions.json | 2 +- trains/community/homepage/app_versions.json | 2 +- trains/community/homer/app_versions.json | 2 +- .../iconik-storage-gateway/app_versions.json | 2 +- trains/community/immich/app_versions.json | 2 +- trains/community/invidious/app_versions.json | 2 +- trains/community/ipfs/app_versions.json | 2 +- trains/community/jellyfin/app_versions.json | 2 +- trains/community/jellyseerr/app_versions.json | 2 +- trains/community/jenkins/app_versions.json | 2 +- trains/community/joplin/app_versions.json | 2 +- trains/community/kapowarr/app_versions.json | 2 +- trains/community/kavita/app_versions.json | 2 +- trains/community/komga/app_versions.json | 2 +- trains/community/lidarr/app_versions.json | 2 +- trains/community/linkding/app_versions.json | 2 +- trains/community/listmonk/app_versions.json | 2 +- trains/community/logseq/app_versions.json | 2 +- trains/community/mealie/app_versions.json | 2 +- trains/community/metube/app_versions.json | 2 +- trains/community/minecraft/app_versions.json | 2 +- trains/community/mineos/app_versions.json | 2 +- trains/community/mumble/app_versions.json | 2 +- trains/community/n8n/app_versions.json | 2 +- trains/community/navidrome/app_versions.json | 2 +- trains/community/netbootxyz/app_versions.json | 2 +- .../nginx-proxy-manager/app_versions.json | 2 +- trains/community/node-red/app_versions.json | 2 +- trains/community/odoo/app_versions.json | 2 +- trains/community/ollama/app_versions.json | 2 +- .../omada-controller/app_versions.json | 2 +- trains/community/open-webui/app_versions.json | 2 +- trains/community/organizr/app_versions.json | 2 +- trains/community/overseerr/app_versions.json | 2 +- trains/community/palworld/app_versions.json | 2 +- .../community/paperless-ngx/app_versions.json | 2 +- trains/community/passbolt/app_versions.json | 2 +- trains/community/penpot/app_versions.json | 2 +- trains/community/pgadmin/app_versions.json | 2 +- trains/community/pigallery2/app_versions.json | 2 +- trains/community/piwigo/app_versions.json | 2 +- trains/community/planka/app_versions.json | 2 +- .../plex-auto-languages/app_versions.json | 2 +- trains/community/portainer/app_versions.json | 2 +- trains/community/postgres/app_versions.json | 2 +- trains/community/prowlarr/app_versions.json | 2 +- .../community/qbittorrent/app_versions.json | 2 +- trains/community/radarr/app_versions.json | 2 +- trains/community/readarr/app_versions.json | 2 +- trains/community/recyclarr/app_versions.json | 2 +- trains/community/redis/app_versions.json | 2 +- trains/community/roundcube/app_versions.json | 2 +- trains/community/rsyncd/app_versions.json | 2 +- trains/community/rust-desk/app_versions.json | 2 +- trains/community/sabnzbd/app_versions.json | 2 +- trains/community/scrutiny/app_versions.json | 2 +- trains/community/searxng/app_versions.json | 2 +- trains/community/sftpgo/app_versions.json | 2 +- trains/community/sonarr/app_versions.json | 2 +- trains/community/tailscale/app_versions.json | 2 +- trains/community/tautulli/app_versions.json | 2 +- trains/community/tdarr/app_versions.json | 2 +- trains/community/terraria/app_versions.json | 2 +- trains/community/tftpd-hpa/app_versions.json | 2 +- .../tiny-media-manager/app_versions.json | 2 +- .../community/transmission/app_versions.json | 2 +- .../twofactor-auth/app_versions.json | 2 +- .../unifi-controller/app_versions.json | 2 +- .../unifi-protect-backup/app_versions.json | 2 +- .../community/uptime-kuma/app_versions.json | 2 +- .../community/vaultwarden/app_versions.json | 2 +- trains/community/vikunja/app_versions.json | 2 +- trains/community/webdav/app_versions.json | 2 +- trains/community/whoogle/app_versions.json | 2 +- trains/community/wordpress/app_versions.json | 2 +- trains/community/zerotier/app_versions.json | 2 +- .../asigra-ds-system/app_versions.json | 16 +- trains/enterprise/minio/app_versions.json | 16 +- trains/enterprise/syncthing/app_versions.json | 16 +- trains/stable/collabora/app_versions.json | 16 +- trains/stable/diskoverdata/app_versions.json | 16 +- .../stable/elastic-search/app_versions.json | 16 +- trains/stable/emby/app_versions.json | 16 +- .../stable/home-assistant/app_versions.json | 16 +- trains/stable/ix-app/app_versions.json | 16 +- trains/stable/minio/app_versions.json | 16 +- trains/stable/netdata/app_versions.json | 16 +- trains/stable/nextcloud/app_versions.json | 16 +- trains/stable/photoprism/app_versions.json | 16 +- trains/stable/pihole/app_versions.json | 16 +- trains/stable/plex/app_versions.json | 16 +- trains/stable/prometheus/app_versions.json | 16 +- trains/stable/storj/app_versions.json | 16 +- trains/stable/syncthing/app_versions.json | 16 +- trains/stable/wg-easy/app_versions.json | 16 +- trains/test/nginx/app_versions.json | 8 +- trains/test/other-nginx/app_versions.json | 4 +- 129 files changed, 431 insertions(+), 431 deletions(-) diff --git a/catalog.json b/catalog.json index 0a6367034e..c49502cfed 100644 --- a/catalog.json +++ b/catalog.json @@ -10,10 +10,10 @@ "healthy_error": null, "home": "https://www.collaboraoffice.com/", "location": "/__w/apps/apps/trains/stable/collabora", - "latest_version": "1.2.1", + "latest_version": "1.2.2", "latest_app_version": "24.04.10.2.1", - "latest_human_version": "24.04.10.2.1_1.2.1", - "last_update": "2024-12-06 13:03:56", + "latest_human_version": "24.04.10.2.1_1.2.2", + "last_update": "2024-12-06 15:12:45", "name": "collabora", "recommended": false, "title": "Collabora", @@ -99,10 +99,10 @@ "healthy_error": null, "home": "https://plex.tv", "location": "/__w/apps/apps/trains/stable/plex", - "latest_version": "1.1.4", + "latest_version": "1.1.5", "latest_app_version": "1.41.2.9200-c6bbc1b53", - "latest_human_version": "1.41.2.9200-c6bbc1b53_1.1.4", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "1.41.2.9200-c6bbc1b53_1.1.5", + "last_update": "2024-12-06 15:12:45", "name": "plex", "recommended": false, "title": "Plex", @@ -177,10 +177,10 @@ "healthy_error": null, "home": "https://www.home-assistant.io/", "location": "/__w/apps/apps/trains/stable/home-assistant", - "latest_version": "1.3.4", + "latest_version": "1.3.5", "latest_app_version": "2024.12.0", - "latest_human_version": "2024.12.0_1.3.4", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "2024.12.0_1.3.5", + "last_update": "2024-12-06 15:12:45", "name": "home-assistant", "recommended": false, "title": "Home Assistant", @@ -252,10 +252,10 @@ "healthy_error": null, "home": "https://photoprism.app/", "location": "/__w/apps/apps/trains/stable/photoprism", - "latest_version": "1.2.0", + "latest_version": "1.2.1", "latest_app_version": "240915", - "latest_human_version": "240915_1.2.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "240915_1.2.1", + "last_update": "2024-12-06 15:12:45", "name": "photoprism", "recommended": false, "title": "Photoprism", @@ -325,10 +325,10 @@ "healthy_error": null, "home": "https://min.io", "location": "/__w/apps/apps/trains/stable/minio", - "latest_version": "1.2.1", + "latest_version": "1.2.2", "latest_app_version": "RELEASE.2024-11-07T00-52-20Z", - "latest_human_version": "RELEASE.2024-11-07T00-52-20Z_1.2.1", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "RELEASE.2024-11-07T00-52-20Z_1.2.2", + "last_update": "2024-12-06 15:12:45", "name": "minio", "recommended": false, "title": "MinIO", @@ -374,10 +374,10 @@ "healthy_error": null, "home": "https://emby.media/", "location": "/__w/apps/apps/trains/stable/emby", - "latest_version": "1.2.3", + "latest_version": "1.2.4", "latest_app_version": "4.8.10.0", - "latest_human_version": "4.8.10.0_1.2.3", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "4.8.10.0_1.2.4", + "last_update": "2024-12-06 15:12:45", "name": "emby", "recommended": false, "title": "Emby Server", @@ -453,10 +453,10 @@ "healthy_error": null, "home": "https://www.netdata.cloud/", "location": "/__w/apps/apps/trains/stable/netdata", - "latest_version": "1.2.0", + "latest_version": "1.2.1", "latest_app_version": "v2.0.3", - "latest_human_version": "v2.0.3_1.2.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "v2.0.3_1.2.1", + "last_update": "2024-12-06 15:12:45", "name": "netdata", "recommended": false, "title": "Netdata", @@ -530,10 +530,10 @@ "healthy_error": null, "home": "https://github.com/wg-easy/wg-easy", "location": "/__w/apps/apps/trains/stable/wg-easy", - "latest_version": "1.1.1", + "latest_version": "1.1.2", "latest_app_version": "14", - "latest_human_version": "14_1.1.1", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "14_1.1.2", + "last_update": "2024-12-06 15:12:45", "name": "wg-easy", "recommended": false, "title": "WG Easy", @@ -590,10 +590,10 @@ "healthy_error": null, "home": "https://prometheus.io", "location": "/__w/apps/apps/trains/stable/prometheus", - "latest_version": "1.2.0", + "latest_version": "1.2.1", "latest_app_version": "v3.0.1", - "latest_human_version": "v3.0.1_1.2.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "v3.0.1_1.2.1", + "last_update": "2024-12-06 15:12:45", "name": "prometheus", "recommended": false, "title": "Prometheus", @@ -638,10 +638,10 @@ "healthy_error": null, "home": "https://syncthing.net/", "location": "/__w/apps/apps/trains/stable/syncthing", - "latest_version": "1.1.0", + "latest_version": "1.1.1", "latest_app_version": "1.28.1", - "latest_human_version": "1.28.1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "1.28.1_1.1.1", + "last_update": "2024-12-06 15:12:45", "name": "syncthing", "recommended": false, "title": "Syncthing", @@ -723,10 +723,10 @@ "healthy_error": null, "home": "https://www.truenas.com/", "location": "/__w/apps/apps/trains/stable/ix-app", - "latest_version": "1.1.1", + "latest_version": "1.1.2", "latest_app_version": "1.0.0", - "latest_human_version": "1.0.0_1.1.1", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "1.0.0_1.1.2", + "last_update": "2024-12-06 15:12:45", "name": "ix-app", "recommended": false, "title": "iX App", @@ -754,10 +754,10 @@ "healthy_error": null, "home": "https://nextcloud.com/", "location": "/__w/apps/apps/trains/stable/nextcloud", - "latest_version": "1.4.15", + "latest_version": "1.4.16", "latest_app_version": "30.0.2", - "latest_human_version": "30.0.2_1.4.15", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "30.0.2_1.4.16", + "last_update": "2024-12-06 15:12:45", "name": "nextcloud", "recommended": false, "title": "Nextcloud", @@ -858,10 +858,10 @@ "healthy_error": null, "home": "https://www.storj.io", "location": "/__w/apps/apps/trains/stable/storj", - "latest_version": "1.2.0", + "latest_version": "1.2.1", "latest_app_version": "6f87ea801-v1.71.2-go1.18.8", - "latest_human_version": "6f87ea801-v1.71.2-go1.18.8_1.2.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "6f87ea801-v1.71.2-go1.18.8_1.2.1", + "last_update": "2024-12-06 15:12:45", "name": "storj", "recommended": false, "title": "Storj", @@ -919,10 +919,10 @@ "healthy_error": null, "home": "https://github.com/diskoverdata/diskover-community", "location": "/__w/apps/apps/trains/stable/diskoverdata", - "latest_version": "1.4.1", + "latest_version": "1.4.2", "latest_app_version": "2.3.0", - "latest_human_version": "2.3.0_1.4.1", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "2.3.0_1.4.2", + "last_update": "2024-12-06 15:12:45", "name": "diskoverdata", "recommended": false, "title": "Diskover Data", @@ -1002,10 +1002,10 @@ "healthy_error": null, "home": "https://pi-hole.net", "location": "/__w/apps/apps/trains/stable/pihole", - "latest_version": "1.2.0", + "latest_version": "1.2.1", "latest_app_version": "2024.07.0", - "latest_human_version": "2024.07.0_1.2.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "2024.07.0_1.2.1", + "last_update": "2024-12-06 15:12:45", "name": "pihole", "recommended": false, "title": "Pi-hole", @@ -1098,10 +1098,10 @@ "healthy_error": null, "home": "https://www.elastic.co", "location": "/__w/apps/apps/trains/stable/elastic-search", - "latest_version": "1.2.0", + "latest_version": "1.2.1", "latest_app_version": "8.16.1", - "latest_human_version": "8.16.1_1.2.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "8.16.1_1.2.1", + "last_update": "2024-12-06 15:12:45", "name": "elastic-search", "recommended": false, "title": "Elastic Search", @@ -1148,7 +1148,7 @@ "latest_version": "1.0.1", "latest_app_version": "v1", "latest_human_version": "v1_1.0.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "other-nginx", "recommended": false, "title": "Other Nginx", @@ -1196,7 +1196,7 @@ "latest_version": "1.0.6", "latest_app_version": "v1", "latest_human_version": "v1_1.0.6", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "nginx", "recommended": false, "title": "Nginx", @@ -1243,10 +1243,10 @@ "healthy_error": null, "home": "https://min.io", "location": "/__w/apps/apps/trains/enterprise/minio", - "latest_version": "1.2.0", + "latest_version": "1.2.1", "latest_app_version": "RELEASE.2024-10-29T16-01-48Z", - "latest_human_version": "RELEASE.2024-10-29T16-01-48Z_1.2.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "RELEASE.2024-10-29T16-01-48Z_1.2.1", + "last_update": "2024-12-06 15:12:45", "name": "minio", "recommended": false, "title": "MinIO", @@ -1292,10 +1292,10 @@ "healthy_error": null, "home": "https://syncthing.net", "location": "/__w/apps/apps/trains/enterprise/syncthing", - "latest_version": "1.1.0", + "latest_version": "1.1.1", "latest_app_version": "1.28.0", - "latest_human_version": "1.28.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "1.28.0_1.1.1", + "last_update": "2024-12-06 15:12:45", "name": "syncthing", "recommended": false, "title": "Syncthing", @@ -1376,10 +1376,10 @@ "healthy_error": null, "home": "https://hub.docker.com/r/asigra/ds-system", "location": "/__w/apps/apps/trains/enterprise/asigra-ds-system", - "latest_version": "1.0.15", + "latest_version": "1.0.16", "latest_app_version": "14.2.0.8", - "latest_human_version": "14.2.0.8_1.0.15", - "last_update": "2024-12-06 13:02:35", + "latest_human_version": "14.2.0.8_1.0.16", + "last_update": "2024-12-06 15:12:45", "name": "asigra-ds-system", "recommended": false, "title": "Asigra DS-System", @@ -1453,7 +1453,7 @@ "latest_version": "1.1.0", "latest_app_version": "0.9.1", "latest_human_version": "0.9.1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "whoogle", "recommended": false, "title": "Whoogle", @@ -1501,7 +1501,7 @@ "latest_version": "1.1.0", "latest_app_version": "1.0.0", "latest_human_version": "1.0.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "rsyncd", "recommended": false, "title": "Rsync Daemon", @@ -1572,7 +1572,7 @@ "latest_version": "1.1.3", "latest_app_version": "v4.1.0", "latest_human_version": "v4.1.0_1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "listmonk", "recommended": false, "title": "Listmonk", @@ -1649,7 +1649,7 @@ "latest_version": "1.12.0", "latest_app_version": "2024.10.2", "latest_human_version": "2024.10.2_1.12.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "minecraft", "recommended": false, "title": "Minecraft", @@ -1715,7 +1715,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.27.02", "latest_human_version": "2.27.02_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "tdarr", "recommended": false, "title": "Tdarr", @@ -1781,7 +1781,7 @@ "latest_version": "1.1.2", "latest_app_version": "v2.15.0", "latest_human_version": "v2.15.0_1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "tautulli", "recommended": false, "title": "Tautulli", @@ -1832,7 +1832,7 @@ "latest_version": "1.2.1", "latest_app_version": "v1.52.0", "latest_human_version": "v1.52.0_1.2.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "autobrr", "recommended": false, "title": "Autobrr", @@ -1881,7 +1881,7 @@ "latest_version": "1.1.0", "latest_app_version": "1.33.2", "latest_human_version": "1.33.2_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "overseerr", "recommended": false, "title": "Overseerr", @@ -1925,7 +1925,7 @@ "latest_version": "1.1.1", "latest_app_version": "1.4.2", "latest_human_version": "1.4.2_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "dockge", "recommended": false, "title": "Dockge", @@ -2005,7 +2005,7 @@ "latest_version": "1.2.0", "latest_app_version": "2024.11.1", "latest_human_version": "2024.11.1_1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "cloudflared", "recommended": false, "title": "Cloudflared", @@ -2051,7 +2051,7 @@ "latest_version": "1.0.12", "latest_app_version": "2.3.3", "latest_human_version": "2.3.3_1.0.12", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "penpot", "recommended": false, "title": "Penpot", @@ -2136,7 +2136,7 @@ "latest_version": "1.1.0", "latest_app_version": "0.7.3-nbxyz1", "latest_human_version": "0.7.3-nbxyz1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "netbootxyz", "recommended": false, "title": "Netboot.xyz", @@ -2220,7 +2220,7 @@ "latest_version": "1.3.0", "latest_app_version": "8.6.9", "latest_human_version": "8.6.9_1.3.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "unifi-controller", "recommended": false, "title": "Unifi Controller", @@ -2267,7 +2267,7 @@ "latest_version": "1.1.7", "latest_app_version": "0.14.1", "latest_human_version": "0.14.1_1.1.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "frigate", "recommended": false, "title": "Frigate", @@ -2340,7 +2340,7 @@ "latest_version": "1.1.0", "latest_app_version": "v0.9.13", "latest_human_version": "v0.9.13_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "homepage", "recommended": false, "title": "Homepage", @@ -2391,7 +2391,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.3.1", "latest_human_version": "2.3.1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "flame", "recommended": false, "title": "Flame", @@ -2450,7 +2450,7 @@ "latest_version": "1.1.7", "latest_app_version": "2.13.5", "latest_human_version": "2.13.5_1.1.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "paperless-ngx", "recommended": false, "title": "Paperless-ngx", @@ -2539,7 +2539,7 @@ "latest_version": "1.1.1", "latest_app_version": "1.0.0", "latest_human_version": "1.0.0_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "tftpd-hpa", "recommended": false, "title": "TFTP Server", @@ -2601,7 +2601,7 @@ "latest_version": "1.1.1", "latest_app_version": "4.0.6", "latest_human_version": "4.0.6_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "transmission", "recommended": false, "title": "Transmission", @@ -2647,7 +2647,7 @@ "latest_version": "1.1.0", "latest_app_version": "latest", "latest_human_version": "latest_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "logseq", "recommended": false, "title": "Logseq", @@ -2691,7 +2691,7 @@ "latest_version": "1.2.0", "latest_app_version": "24.7.17", "latest_human_version": "24.7.17_1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "drawio", "recommended": false, "title": "Draw.io", @@ -2741,7 +2741,7 @@ "latest_version": "1.2.3", "latest_app_version": "3.0.1-beta", "latest_human_version": "3.0.1-beta_1.2.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "joplin", "recommended": false, "title": "Joplin", @@ -2796,7 +2796,7 @@ "latest_version": "1.0.9", "latest_app_version": "v3.3.21", "latest_human_version": "v3.3.21_1.0.9", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "flaresolverr", "recommended": false, "title": "FlareSolverr", @@ -2837,7 +2837,7 @@ "latest_version": "1.1.0", "latest_app_version": "0.8.4", "latest_human_version": "0.8.4_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "kavita", "recommended": false, "title": "Kavita", @@ -2909,7 +2909,7 @@ "latest_version": "1.1.0", "latest_app_version": "4.3.3", "latest_human_version": "4.3.3_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "sabnzbd", "recommended": false, "title": "SABnzbd", @@ -2959,7 +2959,7 @@ "latest_version": "1.2.1", "latest_app_version": "24.11.0", "latest_human_version": "24.11.0_1.2.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "actual-budget", "recommended": false, "title": "Actual Budget", @@ -3009,7 +3009,7 @@ "latest_version": "1.1.0", "latest_app_version": "5.0.13", "latest_human_version": "5.0.13_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "tiny-media-manager", "recommended": false, "title": "Tiny Media Manager", @@ -3073,7 +3073,7 @@ "latest_version": "1.3.5", "latest_app_version": "0.24.5", "latest_human_version": "0.24.5_1.3.5", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "vikunja", "recommended": false, "title": "Vikunja", @@ -3141,7 +3141,7 @@ "latest_version": "1.1.0", "latest_app_version": "4.10.1", "latest_human_version": "4.10.1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "passbolt", "recommended": false, "title": "Passbolt", @@ -3198,7 +3198,7 @@ "latest_version": "1.0.1", "latest_app_version": "3.11.3", "latest_human_version": "3.11.3_1.0.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "iconik-storage-gateway", "recommended": false, "title": "Iconik Storage Gateway", @@ -3242,7 +3242,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.1.0", "latest_human_version": "2.1.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "jellyseerr", "recommended": false, "title": "Jellyseerr", @@ -3288,7 +3288,7 @@ "latest_version": "1.1.11", "latest_app_version": "1.32.5", "latest_human_version": "1.32.5_1.1.11", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "vaultwarden", "recommended": false, "title": "Vaultwarden", @@ -3341,7 +3341,7 @@ "latest_version": "1.1.2", "latest_app_version": "1.13.1", "latest_human_version": "1.13.1_1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "castopod", "recommended": false, "title": "Castopod", @@ -3422,7 +3422,7 @@ "latest_version": "1.4.11", "latest_app_version": "1.71.1", "latest_human_version": "1.71.1_1.4.11", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "name": "n8n", "recommended": false, "title": "n8n", @@ -3486,7 +3486,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.8.3", "latest_human_version": "2.8.3_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "distribution", "recommended": false, "title": "Distribution", @@ -3532,7 +3532,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.10-SNAPSHOT-ocr-es7", "latest_human_version": "2.10-SNAPSHOT-ocr-es7_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "fscrawler", "recommended": false, "title": "FSCrawler", @@ -3578,7 +3578,7 @@ "latest_version": "1.1.1", "latest_app_version": "v0.32.1", "latest_human_version": "v0.32.1_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "ipfs", "recommended": false, "title": "IPFS", @@ -3628,7 +3628,7 @@ "latest_version": "1.1.0", "latest_app_version": "0.53.3", "latest_human_version": "0.53.3_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "navidrome", "recommended": false, "title": "Navidrome", @@ -3676,7 +3676,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.0.0", "latest_human_version": "2.0.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "pigallery2", "recommended": false, "title": "PiGallery2", @@ -3732,7 +3732,7 @@ "latest_version": "1.1.0", "latest_app_version": "latest", "latest_human_version": "latest_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "mineos", "recommended": false, "title": "MineOS", @@ -3799,7 +3799,7 @@ "latest_version": "1.0.4", "latest_app_version": "latest", "latest_human_version": "latest_1.0.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "filestash", "recommended": false, "title": "Filestash", @@ -3848,7 +3848,7 @@ "latest_version": "1.2.2", "latest_app_version": "11.4.0", "latest_human_version": "11.4.0_1.2.2", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "name": "grafana", "recommended": false, "title": "Grafana", @@ -3899,7 +3899,7 @@ "latest_version": "1.2.0", "latest_app_version": "v1.76.6", "latest_human_version": "v1.76.6_1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "tailscale", "recommended": false, "title": "Tailscale", @@ -3969,7 +3969,7 @@ "latest_version": "1.0.13", "latest_app_version": "v0.4.7", "latest_human_version": "v0.4.7_1.0.13", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "open-webui", "recommended": false, "title": "Open WebUI", @@ -4017,7 +4017,7 @@ "latest_version": "1.1.0", "latest_app_version": "2024.12.1-4a8d333d5", "latest_human_version": "2024.12.1-4a8d333d5_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "searxng", "recommended": false, "title": "SearXNG", @@ -4070,7 +4070,7 @@ "latest_version": "1.1.0", "latest_app_version": "1.4.5", "latest_human_version": "1.4.5_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "bazarr", "recommended": false, "title": "Bazarr", @@ -4118,7 +4118,7 @@ "latest_version": "1.1.2", "latest_app_version": "17.0", "latest_human_version": "17.0_1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "odoo", "recommended": false, "title": "Odoo", @@ -4173,7 +4173,7 @@ "latest_version": "1.1.0", "latest_app_version": "15.1.0", "latest_human_version": "15.1.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "piwigo", "recommended": false, "title": "Piwigo", @@ -4252,7 +4252,7 @@ "latest_version": "1.0.5", "latest_app_version": "v0.8.1", "latest_human_version": "v0.8.1_1.0.5", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "scrutiny", "recommended": false, "title": "Scrutiny", @@ -4311,7 +4311,7 @@ "latest_version": "1.3.3", "latest_app_version": "1.27.0.4852", "latest_human_version": "1.27.0.4852_1.3.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "prowlarr", "recommended": false, "title": "Prowlarr", @@ -4357,7 +4357,7 @@ "latest_version": "1.1.0", "latest_app_version": "v1.0.0", "latest_human_version": "v1.0.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "kapowarr", "recommended": false, "title": "Kapowarr", @@ -4405,7 +4405,7 @@ "latest_version": "1.0.3", "latest_app_version": "0.6.22", "latest_human_version": "0.6.22_1.0.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "calibre-web", "recommended": false, "title": "Calibre Web", @@ -4452,7 +4452,7 @@ "latest_version": "1.1.0", "latest_app_version": "1.14.2", "latest_human_version": "1.14.2_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "zerotier", "recommended": false, "title": "Zerotier", @@ -4542,7 +4542,7 @@ "latest_version": "1.3.2", "latest_app_version": "2.17.4", "latest_human_version": "2.17.4_1.3.2", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "name": "audiobookshelf", "recommended": false, "title": "Audiobookshelf", @@ -4593,7 +4593,7 @@ "latest_version": "1.1.0", "latest_app_version": "latest", "latest_human_version": "latest_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "organizr", "recommended": false, "title": "Organizr", @@ -4662,7 +4662,7 @@ "latest_version": "1.1.0", "latest_app_version": "5.4.3", "latest_human_version": "5.4.3_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "twofactor-auth", "recommended": false, "title": "2FAuth", @@ -4710,7 +4710,7 @@ "latest_version": "1.1.0", "latest_app_version": "0.11.0", "latest_human_version": "0.11.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "unifi-protect-backup", "recommended": false, "title": "Unifi Protect Backup", @@ -4772,7 +4772,7 @@ "latest_version": "1.0.8", "latest_app_version": "17.2", "latest_human_version": "17.2_1.0.8", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "postgres", "recommended": false, "title": "Postgres", @@ -4815,7 +4815,7 @@ "latest_version": "1.1.2", "latest_app_version": "4.0.11.2680", "latest_human_version": "4.0.11.2680_1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "sonarr", "recommended": false, "title": "Sonarr", @@ -4864,7 +4864,7 @@ "latest_version": "1.1.2", "latest_app_version": "v0.107.54", "latest_human_version": "v0.107.54_1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "adguard-home", "recommended": false, "title": "AdGuard Home", @@ -4934,7 +4934,7 @@ "latest_version": "1.2.1", "latest_app_version": "2.8.0.4431", "latest_human_version": "2.8.0.4431_1.2.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "lidarr", "recommended": false, "title": "Lidarr", @@ -4983,7 +4983,7 @@ "latest_version": "1.3.2", "latest_app_version": "2.24.1", "latest_human_version": "2.24.1_1.3.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "portainer", "recommended": false, "title": "Portainer", @@ -5065,7 +5065,7 @@ "latest_version": "1.2.0", "latest_app_version": "v1.5.634", "latest_human_version": "v1.5.634_1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "mumble", "recommended": false, "title": "Mumble", @@ -5109,7 +5109,7 @@ "latest_version": "1.2.2", "latest_app_version": "5.15.1.9463", "latest_human_version": "5.15.1.9463_1.2.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "radarr", "recommended": false, "title": "Radarr", @@ -5159,7 +5159,7 @@ "latest_version": "1.1.0", "latest_app_version": "tshock-1.4.4.9-5.2.0-3", "latest_human_version": "tshock-1.4.4.9-5.2.0-3_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "terraria", "recommended": false, "title": "Terraria", @@ -5207,7 +5207,7 @@ "latest_version": "1.0.5", "latest_app_version": "1.7.7", "latest_human_version": "1.7.7_1.0.5", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "gaseous-server", "recommended": false, "title": "Gaseous Server", @@ -5274,7 +5274,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.4.4", "latest_human_version": "2.4.4_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "chia", "recommended": false, "title": "Chia", @@ -5320,7 +5320,7 @@ "latest_version": "1.1.0", "latest_app_version": "3.1.0", "latest_human_version": "3.1.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "dashy", "recommended": false, "title": "Dashy", @@ -5367,7 +5367,7 @@ "latest_version": "1.1.0", "latest_app_version": "6.7.1", "latest_human_version": "6.7.1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "wordpress", "recommended": false, "title": "Wordpress", @@ -5428,7 +5428,7 @@ "latest_version": "1.1.4", "latest_app_version": "1.22.4", "latest_human_version": "1.22.4_1.1.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "gitea", "recommended": false, "title": "Gitea", @@ -5486,7 +5486,7 @@ "latest_version": "1.2.3", "latest_app_version": "5.15", "latest_human_version": "5.15_1.2.3", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "name": "omada-controller", "recommended": false, "title": "Omada Controller", @@ -5554,7 +5554,7 @@ "latest_version": "1.2.0", "latest_app_version": "1.14.1", "latest_human_version": "1.14.1_1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "komga", "recommended": false, "title": "Komga", @@ -5603,7 +5603,7 @@ "latest_version": "1.1.0", "latest_app_version": "v2.6.4", "latest_human_version": "v2.6.4_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "sftpgo", "recommended": false, "title": "SFTPGo", @@ -5647,7 +5647,7 @@ "latest_version": "1.1.0", "latest_app_version": "8.13", "latest_human_version": "8.13_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "pgadmin", "recommended": false, "title": "pgAdmin", @@ -5701,7 +5701,7 @@ "latest_version": "1.1.1", "latest_app_version": "2.4.62", "latest_human_version": "2.4.62_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "webdav", "recommended": false, "title": "WebDAV", @@ -5745,7 +5745,7 @@ "latest_version": "1.1.1", "latest_app_version": "2.479.2-jdk17", "latest_human_version": "2.479.2-jdk17_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "jenkins", "recommended": false, "title": "Jenkins", @@ -5794,7 +5794,7 @@ "latest_version": "1.2.0", "latest_app_version": "latest", "latest_human_version": "latest_1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "plex-auto-languages", "recommended": false, "title": "Plex Auto Languages", @@ -5838,7 +5838,7 @@ "latest_version": "1.2.2", "latest_app_version": "2024-12-05", "latest_human_version": "2024-12-05_1.2.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "metube", "recommended": false, "title": "MeTube", @@ -5885,7 +5885,7 @@ "latest_version": "1.1.0", "latest_app_version": "1.1.11-1", "latest_human_version": "1.1.11-1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "rust-desk", "recommended": false, "title": "Rust Desk", @@ -5930,7 +5930,7 @@ "latest_version": "1.1.2", "latest_app_version": "palworld", "latest_human_version": "palworld_1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "palworld", "recommended": false, "title": "Palworld", @@ -6008,7 +6008,7 @@ "latest_version": "1.1.3", "latest_app_version": "latest", "latest_human_version": "latest_1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "briefkasten", "recommended": false, "title": "Briefkasten", @@ -6063,7 +6063,7 @@ "latest_version": "1.7.8", "latest_app_version": "v1.122.0", "latest_human_version": "v1.122.0_1.7.8", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "name": "immich", "recommended": false, "title": "Immich", @@ -6135,7 +6135,7 @@ "latest_version": "1.0.7", "latest_app_version": "2.0.0-beta.0", "latest_human_version": "2.0.0-beta.0_1.0.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "uptime-kuma", "recommended": false, "title": "Uptime Kuma", @@ -6187,7 +6187,7 @@ "latest_version": "1.1.0", "latest_app_version": "v2.8.2", "latest_human_version": "v2.8.2_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "ddns-updater", "recommended": false, "title": "DDNS Updater", @@ -6235,7 +6235,7 @@ "latest_version": "1.1.3", "latest_app_version": "2.20241110.0", "latest_human_version": "2.20241110.0_1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "invidious", "recommended": false, "title": "Invidious", @@ -6293,7 +6293,7 @@ "latest_version": "1.1.2", "latest_app_version": "0.4.4.2686", "latest_human_version": "0.4.4.2686_1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "readarr", "recommended": false, "title": "Readarr", @@ -6343,7 +6343,7 @@ "latest_version": "1.1.0", "latest_app_version": "7.4.0", "latest_human_version": "7.4.0_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "recyclarr", "recommended": false, "title": "Recyclarr", @@ -6389,7 +6389,7 @@ "latest_version": "2.1.0", "latest_app_version": "v24.09.1", "latest_human_version": "v24.09.1_2.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "handbrake", "recommended": false, "title": "Handbrake", @@ -6464,7 +6464,7 @@ "latest_version": "2.1.2", "latest_app_version": "v24.12.1", "latest_human_version": "v24.12.1_2.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "homer", "recommended": false, "title": "Homer", @@ -6508,7 +6508,7 @@ "latest_version": "1.2.6", "latest_app_version": "1.1.2-2", "latest_human_version": "1.1.2-2_1.2.6", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "clamav", "recommended": false, "title": "ClamAV", @@ -6574,7 +6574,7 @@ "latest_version": "1.0.16", "latest_app_version": "0.5.0", "latest_human_version": "0.5.0_1.0.16", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "name": "ollama", "recommended": false, "title": "Ollama", @@ -6618,7 +6618,7 @@ "latest_version": "1.1.0", "latest_app_version": "4.0.5", "latest_human_version": "4.0.5_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "node-red", "recommended": false, "title": "Node-RED", @@ -6664,7 +6664,7 @@ "latest_version": "1.2.0", "latest_app_version": "v2.31.2", "latest_human_version": "v2.31.2_1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "filebrowser", "recommended": false, "title": "File Browser", @@ -6714,7 +6714,7 @@ "latest_version": "1.0.2", "latest_app_version": "2.0.20", "latest_human_version": "2.0.20_1.0.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "eclipse-mosquitto", "recommended": false, "title": "Eclipse Mosquitto", @@ -6759,7 +6759,7 @@ "latest_version": "1.1.4", "latest_app_version": "1.36.0", "latest_human_version": "1.36.0_1.1.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "linkding", "recommended": false, "title": "Linkding", @@ -6812,7 +6812,7 @@ "latest_version": "1.0.3", "latest_app_version": "7.22.0", "latest_human_version": "7.22.0_1.0.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "calibre", "recommended": false, "title": "Calibre", @@ -6886,7 +6886,7 @@ "latest_version": "1.1.6", "latest_app_version": "1.24.3", "latest_human_version": "1.24.3_1.1.6", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "planka", "recommended": false, "title": "Planka", @@ -6941,7 +6941,7 @@ "latest_version": "1.1.8", "latest_app_version": "5.0.2", "latest_human_version": "5.0.2_1.1.8", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "qbittorrent", "recommended": false, "title": "qBittorrent", @@ -6989,7 +6989,7 @@ "latest_version": "1.3.6", "latest_app_version": "version-6.1.24", "latest_human_version": "version-6.1.24_1.3.6", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "name": "firefly-iii", "recommended": false, "title": "Firefly III", @@ -7076,7 +7076,7 @@ "latest_version": "1.1.1", "latest_app_version": "7.4.1", "latest_human_version": "7.4.1_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "redis", "recommended": false, "title": "Redis", @@ -7121,7 +7121,7 @@ "latest_version": "1.1.7", "latest_app_version": "10.10.3", "latest_human_version": "10.10.3_1.1.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "jellyfin", "recommended": false, "title": "Jellyfin", @@ -7173,7 +7173,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.1.1", "latest_human_version": "2.1.1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "deluge", "recommended": false, "title": "Deluge", @@ -7239,7 +7239,7 @@ "latest_version": "1.3.4", "latest_app_version": "v2.3.0", "latest_human_version": "v2.3.0_1.3.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "mealie", "recommended": false, "title": "Mealie", @@ -7292,7 +7292,7 @@ "latest_version": "1.2.4", "latest_app_version": "1.24.3", "latest_human_version": "1.24.3_1.2.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "freshrss", "recommended": false, "title": "FreshRSS", @@ -7360,7 +7360,7 @@ "latest_version": "1.1.1", "latest_app_version": "0.15.7", "latest_human_version": "0.15.7_1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "homarr", "recommended": false, "title": "Homarr", @@ -7408,7 +7408,7 @@ "latest_version": "1.1.3", "latest_app_version": "1.6.9-apache", "latest_human_version": "1.6.9-apache_1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "roundcube", "recommended": false, "title": "Roundcube", @@ -7487,7 +7487,7 @@ "latest_version": "1.1.0", "latest_app_version": "2.12.1", "latest_human_version": "2.12.1_1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "name": "nginx-proxy-manager", "recommended": false, "title": "Nginx Proxy Manager", diff --git a/trains/community/actual-budget/app_versions.json b/trains/community/actual-budget/app_versions.json index 73e04f260c..85bddffd10 100644 --- a/trains/community/actual-budget/app_versions.json +++ b/trains/community/actual-budget/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/actual-budget/1.2.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "24.11.0_1.2.1", "version": "1.2.1", diff --git a/trains/community/adguard-home/app_versions.json b/trains/community/adguard-home/app_versions.json index 62fa4c88d1..d78565d42e 100644 --- a/trains/community/adguard-home/app_versions.json +++ b/trains/community/adguard-home/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/adguard-home/1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v0.107.54_1.1.2", "version": "1.1.2", diff --git a/trains/community/audiobookshelf/app_versions.json b/trains/community/audiobookshelf/app_versions.json index ed3ad02db5..2cd782efc2 100644 --- a/trains/community/audiobookshelf/app_versions.json +++ b/trains/community/audiobookshelf/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/audiobookshelf/1.3.2", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.17.4_1.3.2", "version": "1.3.2", diff --git a/trains/community/autobrr/app_versions.json b/trains/community/autobrr/app_versions.json index 3dfc8d9216..a3b6c8d27e 100644 --- a/trains/community/autobrr/app_versions.json +++ b/trains/community/autobrr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/autobrr/1.2.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1.52.0_1.2.1", "version": "1.2.1", diff --git a/trains/community/bazarr/app_versions.json b/trains/community/bazarr/app_versions.json index 7e3e2d7a52..1386d952fa 100644 --- a/trains/community/bazarr/app_versions.json +++ b/trains/community/bazarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/bazarr/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.4.5_1.1.0", "version": "1.1.0", diff --git a/trains/community/briefkasten/app_versions.json b/trains/community/briefkasten/app_versions.json index 45c9b8139b..5fba689d32 100644 --- a/trains/community/briefkasten/app_versions.json +++ b/trains/community/briefkasten/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/briefkasten/1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "latest_1.1.3", "version": "1.1.3", diff --git a/trains/community/calibre-web/app_versions.json b/trains/community/calibre-web/app_versions.json index 270efe8a31..0e1fc6bc68 100644 --- a/trains/community/calibre-web/app_versions.json +++ b/trains/community/calibre-web/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/calibre-web/1.0.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.6.22_1.0.3", "version": "1.0.3", diff --git a/trains/community/calibre/app_versions.json b/trains/community/calibre/app_versions.json index 63bd626825..3284f778a3 100644 --- a/trains/community/calibre/app_versions.json +++ b/trains/community/calibre/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/calibre/1.0.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "7.22.0_1.0.3", "version": "1.0.3", diff --git a/trains/community/castopod/app_versions.json b/trains/community/castopod/app_versions.json index dec6df0480..15a09583fb 100644 --- a/trains/community/castopod/app_versions.json +++ b/trains/community/castopod/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/castopod/1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.13.1_1.1.2", "version": "1.1.2", diff --git a/trains/community/chia/app_versions.json b/trains/community/chia/app_versions.json index 6b6d8181d0..400a6024c8 100644 --- a/trains/community/chia/app_versions.json +++ b/trains/community/chia/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/chia/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.4.4_1.1.0", "version": "1.1.0", diff --git a/trains/community/clamav/app_versions.json b/trains/community/clamav/app_versions.json index b5eabd7403..9f895f77f4 100644 --- a/trains/community/clamav/app_versions.json +++ b/trains/community/clamav/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/clamav/1.2.6", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.1.2-2_1.2.6", "version": "1.2.6", diff --git a/trains/community/cloudflared/app_versions.json b/trains/community/cloudflared/app_versions.json index ac0c34413e..df670409ed 100644 --- a/trains/community/cloudflared/app_versions.json +++ b/trains/community/cloudflared/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/cloudflared/1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2024.11.1_1.2.0", "version": "1.2.0", diff --git a/trains/community/dashy/app_versions.json b/trains/community/dashy/app_versions.json index 07ce704dfa..b75184c99a 100644 --- a/trains/community/dashy/app_versions.json +++ b/trains/community/dashy/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/dashy/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "3.1.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/ddns-updater/app_versions.json b/trains/community/ddns-updater/app_versions.json index f582c6d815..b6bfbf5434 100644 --- a/trains/community/ddns-updater/app_versions.json +++ b/trains/community/ddns-updater/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/ddns-updater/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v2.8.2_1.1.0", "version": "1.1.0", diff --git a/trains/community/deluge/app_versions.json b/trains/community/deluge/app_versions.json index 779d5abf85..eeb1e666a6 100644 --- a/trains/community/deluge/app_versions.json +++ b/trains/community/deluge/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/deluge/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.1.1_1.1.0", "version": "1.1.0", diff --git a/trains/community/distribution/app_versions.json b/trains/community/distribution/app_versions.json index 7317a878f3..70bf352832 100644 --- a/trains/community/distribution/app_versions.json +++ b/trains/community/distribution/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/distribution/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.8.3_1.1.0", "version": "1.1.0", diff --git a/trains/community/dockge/app_versions.json b/trains/community/dockge/app_versions.json index 48313a9573..436ca8dfaf 100644 --- a/trains/community/dockge/app_versions.json +++ b/trains/community/dockge/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/dockge/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.4.2_1.1.1", "version": "1.1.1", diff --git a/trains/community/drawio/app_versions.json b/trains/community/drawio/app_versions.json index f59f3e49b8..862ed8e9b0 100644 --- a/trains/community/drawio/app_versions.json +++ b/trains/community/drawio/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/drawio/1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "24.7.17_1.2.0", "version": "1.2.0", diff --git a/trains/community/eclipse-mosquitto/app_versions.json b/trains/community/eclipse-mosquitto/app_versions.json index adc8e134e8..ebeb840dd6 100644 --- a/trains/community/eclipse-mosquitto/app_versions.json +++ b/trains/community/eclipse-mosquitto/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/eclipse-mosquitto/1.0.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.0.20_1.0.2", "version": "1.0.2", diff --git a/trains/community/filebrowser/app_versions.json b/trains/community/filebrowser/app_versions.json index d49eddf527..f0e0e7a6c7 100644 --- a/trains/community/filebrowser/app_versions.json +++ b/trains/community/filebrowser/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/filebrowser/1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v2.31.2_1.2.0", "version": "1.2.0", diff --git a/trains/community/filestash/app_versions.json b/trains/community/filestash/app_versions.json index 0f4b623e79..4a4c4c3ada 100644 --- a/trains/community/filestash/app_versions.json +++ b/trains/community/filestash/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/filestash/1.0.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "latest_1.0.4", "version": "1.0.4", diff --git a/trains/community/firefly-iii/app_versions.json b/trains/community/firefly-iii/app_versions.json index 4d4a600f8e..2ec2a270f9 100644 --- a/trains/community/firefly-iii/app_versions.json +++ b/trains/community/firefly-iii/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/firefly-iii/1.3.6", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "version-6.1.24_1.3.6", "version": "1.3.6", diff --git a/trains/community/flame/app_versions.json b/trains/community/flame/app_versions.json index d146dd6743..a4e8b5f0ed 100644 --- a/trains/community/flame/app_versions.json +++ b/trains/community/flame/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/flame/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.3.1_1.1.0", "version": "1.1.0", diff --git a/trains/community/flaresolverr/app_versions.json b/trains/community/flaresolverr/app_versions.json index 856c344847..e430573f9b 100644 --- a/trains/community/flaresolverr/app_versions.json +++ b/trains/community/flaresolverr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/flaresolverr/1.0.9", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v3.3.21_1.0.9", "version": "1.0.9", diff --git a/trains/community/freshrss/app_versions.json b/trains/community/freshrss/app_versions.json index 37f436d40a..2e518e3a06 100644 --- a/trains/community/freshrss/app_versions.json +++ b/trains/community/freshrss/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/freshrss/1.2.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.24.3_1.2.4", "version": "1.2.4", diff --git a/trains/community/frigate/app_versions.json b/trains/community/frigate/app_versions.json index 35649626a5..cfb6011851 100644 --- a/trains/community/frigate/app_versions.json +++ b/trains/community/frigate/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/frigate/1.1.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.14.1_1.1.7", "version": "1.1.7", diff --git a/trains/community/fscrawler/app_versions.json b/trains/community/fscrawler/app_versions.json index 2ef1a83180..e2db33471e 100644 --- a/trains/community/fscrawler/app_versions.json +++ b/trains/community/fscrawler/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/fscrawler/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.10-SNAPSHOT-ocr-es7_1.1.0", "version": "1.1.0", diff --git a/trains/community/gaseous-server/app_versions.json b/trains/community/gaseous-server/app_versions.json index 78ed00e7ba..bb5d3b50d7 100644 --- a/trains/community/gaseous-server/app_versions.json +++ b/trains/community/gaseous-server/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/gaseous-server/1.0.5", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.7.7_1.0.5", "version": "1.0.5", diff --git a/trains/community/gitea/app_versions.json b/trains/community/gitea/app_versions.json index aac5274b49..a620a70a9d 100644 --- a/trains/community/gitea/app_versions.json +++ b/trains/community/gitea/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/gitea/1.1.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.22.4_1.1.4", "version": "1.1.4", diff --git a/trains/community/grafana/app_versions.json b/trains/community/grafana/app_versions.json index 7e9d3cab3d..327fc49158 100644 --- a/trains/community/grafana/app_versions.json +++ b/trains/community/grafana/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/grafana/1.2.2", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "11.4.0_1.2.2", "version": "1.2.2", diff --git a/trains/community/handbrake/app_versions.json b/trains/community/handbrake/app_versions.json index 977eff8d3e..fd8dbc6c5a 100644 --- a/trains/community/handbrake/app_versions.json +++ b/trains/community/handbrake/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/handbrake/2.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v24.09.1_2.1.0", "version": "2.1.0", diff --git a/trains/community/homarr/app_versions.json b/trains/community/homarr/app_versions.json index 237185f1d1..9e96f7361d 100644 --- a/trains/community/homarr/app_versions.json +++ b/trains/community/homarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/homarr/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.15.7_1.1.1", "version": "1.1.1", diff --git a/trains/community/homepage/app_versions.json b/trains/community/homepage/app_versions.json index 1169473de7..84486a4272 100644 --- a/trains/community/homepage/app_versions.json +++ b/trains/community/homepage/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/homepage/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v0.9.13_1.1.0", "version": "1.1.0", diff --git a/trains/community/homer/app_versions.json b/trains/community/homer/app_versions.json index cff5790980..4473fe8e16 100644 --- a/trains/community/homer/app_versions.json +++ b/trains/community/homer/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/homer/2.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v24.12.1_2.1.2", "version": "2.1.2", diff --git a/trains/community/iconik-storage-gateway/app_versions.json b/trains/community/iconik-storage-gateway/app_versions.json index 4828151b17..4a8e670099 100644 --- a/trains/community/iconik-storage-gateway/app_versions.json +++ b/trains/community/iconik-storage-gateway/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/iconik-storage-gateway/1.0.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "3.11.3_1.0.1", "version": "1.0.1", diff --git a/trains/community/immich/app_versions.json b/trains/community/immich/app_versions.json index 5132ccd53f..00379787b1 100644 --- a/trains/community/immich/app_versions.json +++ b/trains/community/immich/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/immich/1.7.8", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1.122.0_1.7.8", "version": "1.7.8", diff --git a/trains/community/invidious/app_versions.json b/trains/community/invidious/app_versions.json index 8ed231f95f..cc0ce3abe7 100644 --- a/trains/community/invidious/app_versions.json +++ b/trains/community/invidious/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/invidious/1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.20241110.0_1.1.3", "version": "1.1.3", diff --git a/trains/community/ipfs/app_versions.json b/trains/community/ipfs/app_versions.json index 8ef4423a9f..9a4ffafe7e 100644 --- a/trains/community/ipfs/app_versions.json +++ b/trains/community/ipfs/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/ipfs/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v0.32.1_1.1.1", "version": "1.1.1", diff --git a/trains/community/jellyfin/app_versions.json b/trains/community/jellyfin/app_versions.json index f2559eb2c6..c14b1b5491 100644 --- a/trains/community/jellyfin/app_versions.json +++ b/trains/community/jellyfin/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/jellyfin/1.1.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "10.10.3_1.1.7", "version": "1.1.7", diff --git a/trains/community/jellyseerr/app_versions.json b/trains/community/jellyseerr/app_versions.json index f84cf88a9c..d0593ce94f 100644 --- a/trains/community/jellyseerr/app_versions.json +++ b/trains/community/jellyseerr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/jellyseerr/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.1.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/jenkins/app_versions.json b/trains/community/jenkins/app_versions.json index b549b3049f..0e330a1ee3 100644 --- a/trains/community/jenkins/app_versions.json +++ b/trains/community/jenkins/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/jenkins/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.479.2-jdk17_1.1.1", "version": "1.1.1", diff --git a/trains/community/joplin/app_versions.json b/trains/community/joplin/app_versions.json index 1bf3f05778..74886e2016 100644 --- a/trains/community/joplin/app_versions.json +++ b/trains/community/joplin/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/joplin/1.2.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "3.0.1-beta_1.2.3", "version": "1.2.3", diff --git a/trains/community/kapowarr/app_versions.json b/trains/community/kapowarr/app_versions.json index 7325f1524f..8bd31c03c4 100644 --- a/trains/community/kapowarr/app_versions.json +++ b/trains/community/kapowarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/kapowarr/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1.0.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/kavita/app_versions.json b/trains/community/kavita/app_versions.json index bdf7146ae1..42be15a2de 100644 --- a/trains/community/kavita/app_versions.json +++ b/trains/community/kavita/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/kavita/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.8.4_1.1.0", "version": "1.1.0", diff --git a/trains/community/komga/app_versions.json b/trains/community/komga/app_versions.json index c210c4be4b..2ad6287e8d 100644 --- a/trains/community/komga/app_versions.json +++ b/trains/community/komga/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/komga/1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.14.1_1.2.0", "version": "1.2.0", diff --git a/trains/community/lidarr/app_versions.json b/trains/community/lidarr/app_versions.json index 0ec82230cc..3264f6a54f 100644 --- a/trains/community/lidarr/app_versions.json +++ b/trains/community/lidarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/lidarr/1.2.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.8.0.4431_1.2.1", "version": "1.2.1", diff --git a/trains/community/linkding/app_versions.json b/trains/community/linkding/app_versions.json index f8ab87e8c6..de01262853 100644 --- a/trains/community/linkding/app_versions.json +++ b/trains/community/linkding/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/linkding/1.1.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.36.0_1.1.4", "version": "1.1.4", diff --git a/trains/community/listmonk/app_versions.json b/trains/community/listmonk/app_versions.json index 37ae490104..cc35dbd7b3 100644 --- a/trains/community/listmonk/app_versions.json +++ b/trains/community/listmonk/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/listmonk/1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v4.1.0_1.1.3", "version": "1.1.3", diff --git a/trains/community/logseq/app_versions.json b/trains/community/logseq/app_versions.json index 97847981da..cc40e8ad26 100644 --- a/trains/community/logseq/app_versions.json +++ b/trains/community/logseq/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/logseq/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "latest_1.1.0", "version": "1.1.0", diff --git a/trains/community/mealie/app_versions.json b/trains/community/mealie/app_versions.json index 844ec53b4b..82a3915a47 100644 --- a/trains/community/mealie/app_versions.json +++ b/trains/community/mealie/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/mealie/1.3.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v2.3.0_1.3.4", "version": "1.3.4", diff --git a/trains/community/metube/app_versions.json b/trains/community/metube/app_versions.json index 58be006e20..6242030f22 100644 --- a/trains/community/metube/app_versions.json +++ b/trains/community/metube/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/metube/1.2.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2024-12-05_1.2.2", "version": "1.2.2", diff --git a/trains/community/minecraft/app_versions.json b/trains/community/minecraft/app_versions.json index 32f6bf5576..b42b92fc08 100644 --- a/trains/community/minecraft/app_versions.json +++ b/trains/community/minecraft/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/minecraft/1.12.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2024.10.2_1.12.0", "version": "1.12.0", diff --git a/trains/community/mineos/app_versions.json b/trains/community/mineos/app_versions.json index 7e80051de2..4c4a282dcb 100644 --- a/trains/community/mineos/app_versions.json +++ b/trains/community/mineos/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/mineos/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "latest_1.1.0", "version": "1.1.0", diff --git a/trains/community/mumble/app_versions.json b/trains/community/mumble/app_versions.json index 0086d83e9e..8437cd09ee 100644 --- a/trains/community/mumble/app_versions.json +++ b/trains/community/mumble/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/mumble/1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1.5.634_1.2.0", "version": "1.2.0", diff --git a/trains/community/n8n/app_versions.json b/trains/community/n8n/app_versions.json index 0114fc6f71..a3422aba12 100644 --- a/trains/community/n8n/app_versions.json +++ b/trains/community/n8n/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/n8n/1.4.11", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.71.1_1.4.11", "version": "1.4.11", diff --git a/trains/community/navidrome/app_versions.json b/trains/community/navidrome/app_versions.json index 664448daed..c94890c00b 100644 --- a/trains/community/navidrome/app_versions.json +++ b/trains/community/navidrome/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/navidrome/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.53.3_1.1.0", "version": "1.1.0", diff --git a/trains/community/netbootxyz/app_versions.json b/trains/community/netbootxyz/app_versions.json index ddd22c3eb7..f4ec543a80 100644 --- a/trains/community/netbootxyz/app_versions.json +++ b/trains/community/netbootxyz/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/netbootxyz/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.7.3-nbxyz1_1.1.0", "version": "1.1.0", diff --git a/trains/community/nginx-proxy-manager/app_versions.json b/trains/community/nginx-proxy-manager/app_versions.json index d946e400ef..f7e26b7e92 100644 --- a/trains/community/nginx-proxy-manager/app_versions.json +++ b/trains/community/nginx-proxy-manager/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/nginx-proxy-manager/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.12.1_1.1.0", "version": "1.1.0", diff --git a/trains/community/node-red/app_versions.json b/trains/community/node-red/app_versions.json index 5c841b1c35..647724471c 100644 --- a/trains/community/node-red/app_versions.json +++ b/trains/community/node-red/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/node-red/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "4.0.5_1.1.0", "version": "1.1.0", diff --git a/trains/community/odoo/app_versions.json b/trains/community/odoo/app_versions.json index 23a3a6ae43..e6897caff0 100644 --- a/trains/community/odoo/app_versions.json +++ b/trains/community/odoo/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/odoo/1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "17.0_1.1.2", "version": "1.1.2", diff --git a/trains/community/ollama/app_versions.json b/trains/community/ollama/app_versions.json index 9d62bb3ba4..30fc9ed5da 100644 --- a/trains/community/ollama/app_versions.json +++ b/trains/community/ollama/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/ollama/1.0.16", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.5.0_1.0.16", "version": "1.0.16", diff --git a/trains/community/omada-controller/app_versions.json b/trains/community/omada-controller/app_versions.json index 6970f59ad8..2f06681a98 100644 --- a/trains/community/omada-controller/app_versions.json +++ b/trains/community/omada-controller/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/omada-controller/1.2.3", - "last_update": "2024-12-06 13:03:56", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "5.15_1.2.3", "version": "1.2.3", diff --git a/trains/community/open-webui/app_versions.json b/trains/community/open-webui/app_versions.json index 2f89cf9a92..8aadc28f07 100644 --- a/trains/community/open-webui/app_versions.json +++ b/trains/community/open-webui/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/open-webui/1.0.13", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v0.4.7_1.0.13", "version": "1.0.13", diff --git a/trains/community/organizr/app_versions.json b/trains/community/organizr/app_versions.json index 05f15c410e..51b8c5f255 100644 --- a/trains/community/organizr/app_versions.json +++ b/trains/community/organizr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/organizr/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "latest_1.1.0", "version": "1.1.0", diff --git a/trains/community/overseerr/app_versions.json b/trains/community/overseerr/app_versions.json index 51309d9efb..81b9488157 100644 --- a/trains/community/overseerr/app_versions.json +++ b/trains/community/overseerr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/overseerr/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.33.2_1.1.0", "version": "1.1.0", diff --git a/trains/community/palworld/app_versions.json b/trains/community/palworld/app_versions.json index a089fd2967..2e30c3c1bf 100644 --- a/trains/community/palworld/app_versions.json +++ b/trains/community/palworld/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/palworld/1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "palworld_1.1.2", "version": "1.1.2", diff --git a/trains/community/paperless-ngx/app_versions.json b/trains/community/paperless-ngx/app_versions.json index a257364752..4033975f3b 100644 --- a/trains/community/paperless-ngx/app_versions.json +++ b/trains/community/paperless-ngx/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/paperless-ngx/1.1.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.13.5_1.1.7", "version": "1.1.7", diff --git a/trains/community/passbolt/app_versions.json b/trains/community/passbolt/app_versions.json index ced7184c4d..376a682247 100644 --- a/trains/community/passbolt/app_versions.json +++ b/trains/community/passbolt/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/passbolt/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "4.10.1_1.1.0", "version": "1.1.0", diff --git a/trains/community/penpot/app_versions.json b/trains/community/penpot/app_versions.json index ec73f1cbd3..125f46c7b1 100644 --- a/trains/community/penpot/app_versions.json +++ b/trains/community/penpot/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/penpot/1.0.12", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.3.3_1.0.12", "version": "1.0.12", diff --git a/trains/community/pgadmin/app_versions.json b/trains/community/pgadmin/app_versions.json index 9c56ec2355..65a1f08ec5 100644 --- a/trains/community/pgadmin/app_versions.json +++ b/trains/community/pgadmin/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/pgadmin/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "8.13_1.1.0", "version": "1.1.0", diff --git a/trains/community/pigallery2/app_versions.json b/trains/community/pigallery2/app_versions.json index 4d62437bf2..b6916653ec 100644 --- a/trains/community/pigallery2/app_versions.json +++ b/trains/community/pigallery2/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/pigallery2/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.0.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/piwigo/app_versions.json b/trains/community/piwigo/app_versions.json index 11ebd5235e..69fbd090a0 100644 --- a/trains/community/piwigo/app_versions.json +++ b/trains/community/piwigo/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/piwigo/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "15.1.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/planka/app_versions.json b/trains/community/planka/app_versions.json index 29346ddf80..841a8c8d5e 100644 --- a/trains/community/planka/app_versions.json +++ b/trains/community/planka/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/planka/1.1.6", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.24.3_1.1.6", "version": "1.1.6", diff --git a/trains/community/plex-auto-languages/app_versions.json b/trains/community/plex-auto-languages/app_versions.json index b49d235f19..45a9b108ae 100644 --- a/trains/community/plex-auto-languages/app_versions.json +++ b/trains/community/plex-auto-languages/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/plex-auto-languages/1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "latest_1.2.0", "version": "1.2.0", diff --git a/trains/community/portainer/app_versions.json b/trains/community/portainer/app_versions.json index 1987ba3745..0bef527adb 100644 --- a/trains/community/portainer/app_versions.json +++ b/trains/community/portainer/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/portainer/1.3.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.24.1_1.3.2", "version": "1.3.2", diff --git a/trains/community/postgres/app_versions.json b/trains/community/postgres/app_versions.json index 59fa81fdc4..0da965a68b 100644 --- a/trains/community/postgres/app_versions.json +++ b/trains/community/postgres/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/postgres/1.0.8", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "17.2_1.0.8", "version": "1.0.8", diff --git a/trains/community/prowlarr/app_versions.json b/trains/community/prowlarr/app_versions.json index 691e0004d4..b55bf04a4c 100644 --- a/trains/community/prowlarr/app_versions.json +++ b/trains/community/prowlarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/prowlarr/1.3.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.27.0.4852_1.3.3", "version": "1.3.3", diff --git a/trains/community/qbittorrent/app_versions.json b/trains/community/qbittorrent/app_versions.json index b611dfdc90..0a111a2d01 100644 --- a/trains/community/qbittorrent/app_versions.json +++ b/trains/community/qbittorrent/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/qbittorrent/1.1.8", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "5.0.2_1.1.8", "version": "1.1.8", diff --git a/trains/community/radarr/app_versions.json b/trains/community/radarr/app_versions.json index 5a82e24874..dc993588ee 100644 --- a/trains/community/radarr/app_versions.json +++ b/trains/community/radarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/radarr/1.2.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "5.15.1.9463_1.2.2", "version": "1.2.2", diff --git a/trains/community/readarr/app_versions.json b/trains/community/readarr/app_versions.json index f49aa2d5b6..0c711bc37b 100644 --- a/trains/community/readarr/app_versions.json +++ b/trains/community/readarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/readarr/1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.4.4.2686_1.1.2", "version": "1.1.2", diff --git a/trains/community/recyclarr/app_versions.json b/trains/community/recyclarr/app_versions.json index e94fb00100..0aa449190c 100644 --- a/trains/community/recyclarr/app_versions.json +++ b/trains/community/recyclarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/recyclarr/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "7.4.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/redis/app_versions.json b/trains/community/redis/app_versions.json index c05dc84b19..a63056dcbd 100644 --- a/trains/community/redis/app_versions.json +++ b/trains/community/redis/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/redis/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "7.4.1_1.1.1", "version": "1.1.1", diff --git a/trains/community/roundcube/app_versions.json b/trains/community/roundcube/app_versions.json index d6b1510eda..8f75e20a5c 100644 --- a/trains/community/roundcube/app_versions.json +++ b/trains/community/roundcube/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/roundcube/1.1.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.6.9-apache_1.1.3", "version": "1.1.3", diff --git a/trains/community/rsyncd/app_versions.json b/trains/community/rsyncd/app_versions.json index be1fa7a58c..5f75d2f7d9 100644 --- a/trains/community/rsyncd/app_versions.json +++ b/trains/community/rsyncd/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/rsyncd/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.0.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/rust-desk/app_versions.json b/trains/community/rust-desk/app_versions.json index de78bf8df2..8db089687c 100644 --- a/trains/community/rust-desk/app_versions.json +++ b/trains/community/rust-desk/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/rust-desk/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.1.11-1_1.1.0", "version": "1.1.0", diff --git a/trains/community/sabnzbd/app_versions.json b/trains/community/sabnzbd/app_versions.json index d588f235c5..478bbd4138 100644 --- a/trains/community/sabnzbd/app_versions.json +++ b/trains/community/sabnzbd/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/sabnzbd/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "4.3.3_1.1.0", "version": "1.1.0", diff --git a/trains/community/scrutiny/app_versions.json b/trains/community/scrutiny/app_versions.json index a65d6b9489..04b73646b9 100644 --- a/trains/community/scrutiny/app_versions.json +++ b/trains/community/scrutiny/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/scrutiny/1.0.5", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v0.8.1_1.0.5", "version": "1.0.5", diff --git a/trains/community/searxng/app_versions.json b/trains/community/searxng/app_versions.json index d6be0f67a8..f934887999 100644 --- a/trains/community/searxng/app_versions.json +++ b/trains/community/searxng/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/searxng/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2024.12.1-4a8d333d5_1.1.0", "version": "1.1.0", diff --git a/trains/community/sftpgo/app_versions.json b/trains/community/sftpgo/app_versions.json index 4766d3305b..7f5aacef92 100644 --- a/trains/community/sftpgo/app_versions.json +++ b/trains/community/sftpgo/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/sftpgo/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v2.6.4_1.1.0", "version": "1.1.0", diff --git a/trains/community/sonarr/app_versions.json b/trains/community/sonarr/app_versions.json index 0dce993f68..e2e6513806 100644 --- a/trains/community/sonarr/app_versions.json +++ b/trains/community/sonarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/sonarr/1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "4.0.11.2680_1.1.2", "version": "1.1.2", diff --git a/trains/community/tailscale/app_versions.json b/trains/community/tailscale/app_versions.json index 55647b15aa..0b45ab72e3 100644 --- a/trains/community/tailscale/app_versions.json +++ b/trains/community/tailscale/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/tailscale/1.2.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1.76.6_1.2.0", "version": "1.2.0", diff --git a/trains/community/tautulli/app_versions.json b/trains/community/tautulli/app_versions.json index 20ecf355ed..8140d342ae 100644 --- a/trains/community/tautulli/app_versions.json +++ b/trains/community/tautulli/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/tautulli/1.1.2", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v2.15.0_1.1.2", "version": "1.1.2", diff --git a/trains/community/tdarr/app_versions.json b/trains/community/tdarr/app_versions.json index 89a626e771..c1f7e4fd4d 100644 --- a/trains/community/tdarr/app_versions.json +++ b/trains/community/tdarr/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/tdarr/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.27.02_1.1.0", "version": "1.1.0", diff --git a/trains/community/terraria/app_versions.json b/trains/community/terraria/app_versions.json index b25f84723e..b851e3325c 100644 --- a/trains/community/terraria/app_versions.json +++ b/trains/community/terraria/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/terraria/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "tshock-1.4.4.9-5.2.0-3_1.1.0", "version": "1.1.0", diff --git a/trains/community/tftpd-hpa/app_versions.json b/trains/community/tftpd-hpa/app_versions.json index ec45d917cc..0705490b1f 100644 --- a/trains/community/tftpd-hpa/app_versions.json +++ b/trains/community/tftpd-hpa/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/tftpd-hpa/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.0.0_1.1.1", "version": "1.1.1", diff --git a/trains/community/tiny-media-manager/app_versions.json b/trains/community/tiny-media-manager/app_versions.json index e5f5937f75..0400d704af 100644 --- a/trains/community/tiny-media-manager/app_versions.json +++ b/trains/community/tiny-media-manager/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/tiny-media-manager/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "5.0.13_1.1.0", "version": "1.1.0", diff --git a/trains/community/transmission/app_versions.json b/trains/community/transmission/app_versions.json index c1cede4aee..69d1fd340b 100644 --- a/trains/community/transmission/app_versions.json +++ b/trains/community/transmission/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/transmission/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "4.0.6_1.1.1", "version": "1.1.1", diff --git a/trains/community/twofactor-auth/app_versions.json b/trains/community/twofactor-auth/app_versions.json index 4d24c131eb..301bfac42e 100644 --- a/trains/community/twofactor-auth/app_versions.json +++ b/trains/community/twofactor-auth/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/twofactor-auth/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "5.4.3_1.1.0", "version": "1.1.0", diff --git a/trains/community/unifi-controller/app_versions.json b/trains/community/unifi-controller/app_versions.json index d96afa50b0..4a5e1ad1fd 100644 --- a/trains/community/unifi-controller/app_versions.json +++ b/trains/community/unifi-controller/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/unifi-controller/1.3.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "8.6.9_1.3.0", "version": "1.3.0", diff --git a/trains/community/unifi-protect-backup/app_versions.json b/trains/community/unifi-protect-backup/app_versions.json index 5dbe63ef6b..9894e1483c 100644 --- a/trains/community/unifi-protect-backup/app_versions.json +++ b/trains/community/unifi-protect-backup/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/unifi-protect-backup/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.11.0_1.1.0", "version": "1.1.0", diff --git a/trains/community/uptime-kuma/app_versions.json b/trains/community/uptime-kuma/app_versions.json index a095b65399..3ba876051b 100644 --- a/trains/community/uptime-kuma/app_versions.json +++ b/trains/community/uptime-kuma/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/uptime-kuma/1.0.7", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.0.0-beta.0_1.0.7", "version": "1.0.7", diff --git a/trains/community/vaultwarden/app_versions.json b/trains/community/vaultwarden/app_versions.json index 934d95a2f9..80fbeaf712 100644 --- a/trains/community/vaultwarden/app_versions.json +++ b/trains/community/vaultwarden/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/vaultwarden/1.1.11", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.32.5_1.1.11", "version": "1.1.11", diff --git a/trains/community/vikunja/app_versions.json b/trains/community/vikunja/app_versions.json index f1758a45e1..ca69eab6fd 100644 --- a/trains/community/vikunja/app_versions.json +++ b/trains/community/vikunja/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/vikunja/1.3.5", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.24.5_1.3.5", "version": "1.3.5", diff --git a/trains/community/webdav/app_versions.json b/trains/community/webdav/app_versions.json index 3ba7ea5a3e..d5d13b83ca 100644 --- a/trains/community/webdav/app_versions.json +++ b/trains/community/webdav/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/webdav/1.1.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "2.4.62_1.1.1", "version": "1.1.1", diff --git a/trains/community/whoogle/app_versions.json b/trains/community/whoogle/app_versions.json index 1f0d753b41..4e09e54c23 100644 --- a/trains/community/whoogle/app_versions.json +++ b/trains/community/whoogle/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/whoogle/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "0.9.1_1.1.0", "version": "1.1.0", diff --git a/trains/community/wordpress/app_versions.json b/trains/community/wordpress/app_versions.json index 097168589d..2b4eb4c96f 100644 --- a/trains/community/wordpress/app_versions.json +++ b/trains/community/wordpress/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/wordpress/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "6.7.1_1.1.0", "version": "1.1.0", diff --git a/trains/community/zerotier/app_versions.json b/trains/community/zerotier/app_versions.json index 16e079ad10..a4e7b2d2e6 100644 --- a/trains/community/zerotier/app_versions.json +++ b/trains/community/zerotier/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/community/zerotier/1.1.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "1.14.2_1.1.0", "version": "1.1.0", diff --git a/trains/enterprise/asigra-ds-system/app_versions.json b/trains/enterprise/asigra-ds-system/app_versions.json index 703bb62bcb..53efac6187 100644 --- a/trains/enterprise/asigra-ds-system/app_versions.json +++ b/trains/enterprise/asigra-ds-system/app_versions.json @@ -1,13 +1,13 @@ { - "1.0.15": { + "1.0.16": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/enterprise/asigra-ds-system/1.0.15", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/enterprise/asigra-ds-system/1.0.16", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "14.2.0.8_1.0.15", - "version": "1.0.15", + "human_version": "14.2.0.8_1.0.16", + "version": "1.0.16", "app_metadata": { "app_version": "14.2.0.8", "capabilities": [ @@ -36,8 +36,8 @@ "restore", "asigra" ], - "lib_version": "2.0.21", - "lib_version_hash": "e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -75,7 +75,7 @@ ], "title": "Asigra DS-System", "train": "enterprise", - "version": "1.0.15" + "version": "1.0.16" }, "schema": { "groups": [ diff --git a/trains/enterprise/minio/app_versions.json b/trains/enterprise/minio/app_versions.json index 4d40dd7f34..cc346fab72 100644 --- a/trains/enterprise/minio/app_versions.json +++ b/trains/enterprise/minio/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.0": { + "1.2.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/enterprise/minio/1.2.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/enterprise/minio/1.2.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "RELEASE.2024-10-29T16-01-48Z_1.2.0", - "version": "1.2.0", + "human_version": "RELEASE.2024-10-29T16-01-48Z_1.2.1", + "version": "1.2.1", "app_metadata": { "app_version": "RELEASE.2024-10-29T16-01-48Z", "capabilities": [], @@ -24,8 +24,8 @@ "cloud", "s3" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -52,7 +52,7 @@ ], "title": "MinIO", "train": "enterprise", - "version": "1.2.0" + "version": "1.2.1" }, "schema": { "groups": [ diff --git a/trains/enterprise/syncthing/app_versions.json b/trains/enterprise/syncthing/app_versions.json index 943a0a4683..239f5ad308 100644 --- a/trains/enterprise/syncthing/app_versions.json +++ b/trains/enterprise/syncthing/app_versions.json @@ -1,13 +1,13 @@ { - "1.1.0": { + "1.1.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/enterprise/syncthing/1.1.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/enterprise/syncthing/1.1.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "1.28.0_1.1.0", - "version": "1.1.0", + "human_version": "1.28.0_1.1.1", + "version": "1.1.1", "app_metadata": { "app_version": "1.28.0", "capabilities": [ @@ -55,8 +55,8 @@ "sync", "file-sharing" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -87,7 +87,7 @@ ], "title": "Syncthing", "train": "enterprise", - "version": "1.1.0" + "version": "1.1.1" }, "schema": { "groups": [ diff --git a/trains/stable/collabora/app_versions.json b/trains/stable/collabora/app_versions.json index 557738c952..979960df8f 100644 --- a/trains/stable/collabora/app_versions.json +++ b/trains/stable/collabora/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.1": { + "1.2.2": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/collabora/1.2.1", - "last_update": "2024-12-06 13:03:56", + "location": "/__w/apps/apps/trains/stable/collabora/1.2.2", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "24.04.10.2.1_1.2.1", - "version": "1.2.1", + "human_version": "24.04.10.2.1_1.2.2", + "version": "1.2.2", "app_metadata": { "app_version": "24.04.10.2.1", "capabilities": [ @@ -56,8 +56,8 @@ "documents", "productivity" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -92,7 +92,7 @@ ], "title": "Collabora", "train": "stable", - "version": "1.2.1" + "version": "1.2.2" }, "schema": { "groups": [ diff --git a/trains/stable/diskoverdata/app_versions.json b/trains/stable/diskoverdata/app_versions.json index 66b58f51ab..1b3b066773 100644 --- a/trains/stable/diskoverdata/app_versions.json +++ b/trains/stable/diskoverdata/app_versions.json @@ -1,13 +1,13 @@ { - "1.4.1": { + "1.4.2": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/diskoverdata/1.4.1", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/diskoverdata/1.4.2", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "2.3.0_1.4.1", - "version": "1.4.1", + "human_version": "2.3.0_1.4.2", + "version": "1.4.2", "app_metadata": { "app_version": "2.3.0", "capabilities": [ @@ -49,8 +49,8 @@ "management", "discovery" ], - "lib_version": "2.0.31", - "lib_version_hash": "e61b4db536830d207e591fea73037ca3f335da01a7e4073bb37392d1ede15873", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -86,7 +86,7 @@ ], "title": "Diskover Data", "train": "stable", - "version": "1.4.1" + "version": "1.4.2" }, "schema": { "groups": [ diff --git a/trains/stable/elastic-search/app_versions.json b/trains/stable/elastic-search/app_versions.json index 5904424b87..333d79eecb 100644 --- a/trains/stable/elastic-search/app_versions.json +++ b/trains/stable/elastic-search/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.0": { + "1.2.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/elastic-search/1.2.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/elastic-search/1.2.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "8.16.1_1.2.0", - "version": "1.2.0", + "human_version": "8.16.1_1.2.1", + "version": "1.2.1", "app_metadata": { "app_version": "8.16.1", "capabilities": [], @@ -22,8 +22,8 @@ "search", "elastic" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -48,7 +48,7 @@ ], "title": "Elastic Search", "train": "stable", - "version": "1.2.0" + "version": "1.2.1" }, "schema": { "groups": [ diff --git a/trains/stable/emby/app_versions.json b/trains/stable/emby/app_versions.json index 8606c2a2d2..32605817fb 100644 --- a/trains/stable/emby/app_versions.json +++ b/trains/stable/emby/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.3": { + "1.2.4": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/emby/1.2.3", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/emby/1.2.4", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "4.8.10.0_1.2.3", - "version": "1.2.3", + "human_version": "4.8.10.0_1.2.4", + "version": "1.2.4", "app_metadata": { "app_version": "4.8.10.0", "capabilities": [ @@ -52,8 +52,8 @@ "tv", "streaming" ], - "lib_version": "2.0.21", - "lib_version_hash": "e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -82,7 +82,7 @@ ], "title": "Emby Server", "train": "stable", - "version": "1.2.3" + "version": "1.2.4" }, "schema": { "groups": [ diff --git a/trains/stable/home-assistant/app_versions.json b/trains/stable/home-assistant/app_versions.json index bccc007209..0e12042e46 100644 --- a/trains/stable/home-assistant/app_versions.json +++ b/trains/stable/home-assistant/app_versions.json @@ -1,13 +1,13 @@ { - "1.3.4": { + "1.3.5": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/home-assistant/1.3.4", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/home-assistant/1.3.5", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "2024.12.0_1.3.4", - "version": "1.3.4", + "human_version": "2024.12.0_1.3.5", + "version": "1.3.5", "app_metadata": { "app_version": "2024.12.0", "capabilities": [ @@ -43,8 +43,8 @@ "home-automation", "assistant" ], - "lib_version": "2.0.21", - "lib_version_hash": "e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -78,7 +78,7 @@ ], "title": "Home Assistant", "train": "stable", - "version": "1.3.4" + "version": "1.3.5" }, "schema": { "groups": [ diff --git a/trains/stable/ix-app/app_versions.json b/trains/stable/ix-app/app_versions.json index 4783c2d91b..af6b2e70a9 100644 --- a/trains/stable/ix-app/app_versions.json +++ b/trains/stable/ix-app/app_versions.json @@ -1,13 +1,13 @@ { - "1.1.1": { + "1.1.2": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/ix-app/1.1.1", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/ix-app/1.1.2", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "1.0.0_1.1.1", - "version": "1.1.1", + "human_version": "1.0.0_1.1.2", + "version": "1.1.2", "app_metadata": { "app_version": "1.0.0", "capabilities": [], @@ -19,8 +19,8 @@ "host_mounts": [], "icon": "https://media.sys.truenas.net/apps/ix-chart/icons/icon.webp", "keywords": [], - "lib_version": "2.0.34", - "lib_version_hash": "54c507c0a47e2a10aee421ec5a67c04f73692bd865d4d5057f57711e322a7951", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -34,7 +34,7 @@ "sources": [], "title": "iX App", "train": "stable", - "version": "1.1.1" + "version": "1.1.2" }, "schema": { "groups": [ diff --git a/trains/stable/minio/app_versions.json b/trains/stable/minio/app_versions.json index 0c3cc8343f..dead35603d 100644 --- a/trains/stable/minio/app_versions.json +++ b/trains/stable/minio/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.1": { + "1.2.2": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/minio/1.2.1", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/minio/1.2.2", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "RELEASE.2024-11-07T00-52-20Z_1.2.1", - "version": "1.2.1", + "human_version": "RELEASE.2024-11-07T00-52-20Z_1.2.2", + "version": "1.2.2", "app_metadata": { "app_version": "RELEASE.2024-11-07T00-52-20Z", "capabilities": [], @@ -23,8 +23,8 @@ "object-storage", "S3" ], - "lib_version": "2.0.21", - "lib_version_hash": "e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -52,7 +52,7 @@ ], "title": "MinIO", "train": "stable", - "version": "1.2.1" + "version": "1.2.2" }, "schema": { "groups": [ diff --git a/trains/stable/netdata/app_versions.json b/trains/stable/netdata/app_versions.json index 51faa205a4..78abe9bda6 100644 --- a/trains/stable/netdata/app_versions.json +++ b/trains/stable/netdata/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.0": { + "1.2.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/netdata/1.2.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/netdata/1.2.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "v2.0.3_1.2.0", - "version": "1.2.0", + "human_version": "v2.0.3_1.2.1", + "version": "1.2.1", "app_metadata": { "app_version": "v2.0.3", "capabilities": [ @@ -73,8 +73,8 @@ "metric", "monitoring" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -105,7 +105,7 @@ ], "title": "Netdata", "train": "stable", - "version": "1.2.0" + "version": "1.2.1" }, "schema": { "groups": [ diff --git a/trains/stable/nextcloud/app_versions.json b/trains/stable/nextcloud/app_versions.json index 05842cc439..8a4a3ef5e6 100644 --- a/trains/stable/nextcloud/app_versions.json +++ b/trains/stable/nextcloud/app_versions.json @@ -1,13 +1,13 @@ { - "1.4.15": { + "1.4.16": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/nextcloud/1.4.15", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/nextcloud/1.4.16", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "30.0.2_1.4.15", - "version": "1.4.15", + "human_version": "30.0.2_1.4.16", + "version": "1.4.16", "app_metadata": { "app_version": "30.0.2", "capabilities": [ @@ -55,8 +55,8 @@ "web", "php" ], - "lib_version": "2.0.21", - "lib_version_hash": "e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -107,7 +107,7 @@ ], "title": "Nextcloud", "train": "stable", - "version": "1.4.15" + "version": "1.4.16" }, "schema": { "groups": [ diff --git a/trains/stable/photoprism/app_versions.json b/trains/stable/photoprism/app_versions.json index c75225f8af..1fe6d20483 100644 --- a/trains/stable/photoprism/app_versions.json +++ b/trains/stable/photoprism/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.0": { + "1.2.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/photoprism/1.2.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/photoprism/1.2.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "240915_1.2.0", - "version": "1.2.0", + "human_version": "240915_1.2.1", + "version": "1.2.1", "app_metadata": { "app_version": "240915", "capabilities": [ @@ -48,8 +48,8 @@ "photos", "image" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -76,7 +76,7 @@ ], "title": "Photoprism", "train": "stable", - "version": "1.2.0" + "version": "1.2.1" }, "schema": { "groups": [ diff --git a/trains/stable/pihole/app_versions.json b/trains/stable/pihole/app_versions.json index 5313fd8c53..bf018aca34 100644 --- a/trains/stable/pihole/app_versions.json +++ b/trains/stable/pihole/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.0": { + "1.2.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/pihole/1.2.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/pihole/1.2.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "2024.07.0_1.2.0", - "version": "1.2.0", + "human_version": "2024.07.0_1.2.1", + "version": "1.2.1", "app_metadata": { "app_version": "2024.07.0", "capabilities": [ @@ -71,8 +71,8 @@ "networking", "dns" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -99,7 +99,7 @@ ], "title": "Pi-hole", "train": "stable", - "version": "1.2.0" + "version": "1.2.1" }, "schema": { "groups": [ diff --git a/trains/stable/plex/app_versions.json b/trains/stable/plex/app_versions.json index 298dcf0409..a18a4dbe55 100644 --- a/trains/stable/plex/app_versions.json +++ b/trains/stable/plex/app_versions.json @@ -1,13 +1,13 @@ { - "1.1.4": { + "1.1.5": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/plex/1.1.4", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/plex/1.1.5", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "1.41.2.9200-c6bbc1b53_1.1.4", - "version": "1.1.4", + "human_version": "1.41.2.9200-c6bbc1b53_1.1.5", + "version": "1.1.5", "app_metadata": { "app_version": "1.41.2.9200-c6bbc1b53", "capabilities": [ @@ -52,8 +52,8 @@ "tv", "streaming" ], - "lib_version": "2.0.21", - "lib_version_hash": "e2faccd282b768e411919a7386a03e8491d1a7fda2da586dcf9af0d412733b8a", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -81,7 +81,7 @@ ], "title": "Plex", "train": "stable", - "version": "1.1.4" + "version": "1.1.5" }, "schema": { "groups": [ diff --git a/trains/stable/prometheus/app_versions.json b/trains/stable/prometheus/app_versions.json index 72799614ba..015033b8e0 100644 --- a/trains/stable/prometheus/app_versions.json +++ b/trains/stable/prometheus/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.0": { + "1.2.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/prometheus/1.2.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/prometheus/1.2.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "v3.0.1_1.2.0", - "version": "1.2.0", + "human_version": "v3.0.1_1.2.1", + "version": "1.2.1", "app_metadata": { "app_version": "v3.0.1", "capabilities": [], @@ -22,8 +22,8 @@ "metrics", "prometheus" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -51,7 +51,7 @@ ], "title": "Prometheus", "train": "stable", - "version": "1.2.0" + "version": "1.2.1" }, "schema": { "groups": [ diff --git a/trains/stable/storj/app_versions.json b/trains/stable/storj/app_versions.json index b194d73d6e..c1d8e91bc3 100644 --- a/trains/stable/storj/app_versions.json +++ b/trains/stable/storj/app_versions.json @@ -1,13 +1,13 @@ { - "1.2.0": { + "1.2.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/storj/1.2.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/storj/1.2.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "6f87ea801-v1.71.2-go1.18.8_1.2.0", - "version": "1.2.0", + "human_version": "6f87ea801-v1.71.2-go1.18.8_1.2.1", + "version": "1.2.1", "app_metadata": { "app_version": "6f87ea801-v1.71.2-go1.18.8", "capabilities": [ @@ -37,8 +37,8 @@ "financial", "file-sharing" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -64,7 +64,7 @@ ], "title": "Storj", "train": "stable", - "version": "1.2.0" + "version": "1.2.1" }, "schema": { "groups": [ diff --git a/trains/stable/syncthing/app_versions.json b/trains/stable/syncthing/app_versions.json index e2db8e4542..05c5d0f6a4 100644 --- a/trains/stable/syncthing/app_versions.json +++ b/trains/stable/syncthing/app_versions.json @@ -1,13 +1,13 @@ { - "1.1.0": { + "1.1.1": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/syncthing/1.1.0", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/syncthing/1.1.1", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "1.28.1_1.1.0", - "version": "1.1.0", + "human_version": "1.28.1_1.1.1", + "version": "1.1.1", "app_metadata": { "app_version": "1.28.1", "capabilities": [ @@ -56,8 +56,8 @@ "file-sharing", "backup" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -88,7 +88,7 @@ ], "title": "Syncthing", "train": "stable", - "version": "1.1.0" + "version": "1.1.1" }, "schema": { "groups": [ diff --git a/trains/stable/wg-easy/app_versions.json b/trains/stable/wg-easy/app_versions.json index 88379f3051..f85bffd061 100644 --- a/trains/stable/wg-easy/app_versions.json +++ b/trains/stable/wg-easy/app_versions.json @@ -1,13 +1,13 @@ { - "1.1.1": { + "1.1.2": { "healthy": true, "supported": true, "healthy_error": null, - "location": "/__w/apps/apps/trains/stable/wg-easy/1.1.1", - "last_update": "2024-12-06 13:02:35", + "location": "/__w/apps/apps/trains/stable/wg-easy/1.1.2", + "last_update": "2024-12-06 15:12:45", "required_features": [], - "human_version": "14_1.1.1", - "version": "1.1.1", + "human_version": "14_1.1.2", + "version": "1.1.2", "app_metadata": { "app_version": "14", "capabilities": [ @@ -36,8 +36,8 @@ "network", "vpn" ], - "lib_version": "2.0.32", - "lib_version_hash": "4a0bf69cccda322e191eab36ab81ca6d0c8e5d64a0b2fa117c609804b55b86c6", + "lib_version": "2.1.0", + "lib_version_hash": "6f8024bfc9f06424dcc9dd3c0391d1b28afb5dddd5dcde2f6a9a0f8de2f74291", "maintainers": [ { "email": "dev@ixsystems.com", @@ -63,7 +63,7 @@ ], "title": "WG Easy", "train": "stable", - "version": "1.1.1" + "version": "1.1.2" }, "schema": { "groups": [ diff --git a/trains/test/nginx/app_versions.json b/trains/test/nginx/app_versions.json index a70752ed37..9e5a8ba326 100644 --- a/trains/test/nginx/app_versions.json +++ b/trains/test/nginx/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/test/nginx/1.0.6", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1_1.0.6", "version": "1.0.6", @@ -107,7 +107,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/test/nginx/1.0.5", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1_1.0.5", "version": "1.0.5", @@ -200,7 +200,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/test/nginx/1.0.4", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1_1.0.4", "version": "1.0.4", @@ -293,7 +293,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/test/nginx/1.0.3", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1_1.0.3", "version": "1.0.3", diff --git a/trains/test/other-nginx/app_versions.json b/trains/test/other-nginx/app_versions.json index 851b57f9c3..a0fb499250 100644 --- a/trains/test/other-nginx/app_versions.json +++ b/trains/test/other-nginx/app_versions.json @@ -4,7 +4,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/test/other-nginx/1.0.1", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1_1.0.1", "version": "1.0.1", @@ -97,7 +97,7 @@ "supported": true, "healthy_error": null, "location": "/__w/apps/apps/trains/test/other-nginx/1.0.0", - "last_update": "2024-12-06 13:02:35", + "last_update": "2024-12-06 15:10:21", "required_features": [], "human_version": "v1_1.0.0", "version": "1.0.0",