From 54c8631de8ee80d34a13e885812fb500b4f8abbb Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 6 Oct 2026 11:51:18 +0200 Subject: [PATCH 01/10] Support CE-style image repo and package suffixes in edge install and upgrade instructions --- .../install/centos/instructions.md | 4 +-- .../install/docker/instructions.md | 2 +- .../install/ubuntu/instructions.md | 4 +-- .../upgrade/centos/instructions.md | 6 ++--- .../upgrade/docker/start_service.md | 4 +-- .../instructions/upgrade/docker/upgrade_db.md | 2 +- .../upgrade/ubuntu/instructions.md | 6 ++--- ...DefaultEdgeInstallInstructionsService.java | 13 +++++++--- ...DefaultEdgeUpgradeInstructionsService.java | 17 ++++++++---- .../server/dao/edge/EdgeEditionStyle.java | 26 +++++++++++++++++++ 10 files changed, 61 insertions(+), 23 deletions(-) create mode 100644 dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java diff --git a/application/src/main/data/json/edge/instructions/install/centos/instructions.md b/application/src/main/data/json/edge/instructions/install/centos/instructions.md index b6b68825be..3010f83666 100644 --- a/application/src/main/data/json/edge/instructions/install/centos/instructions.md +++ b/application/src/main/data/json/edge/instructions/install/centos/instructions.md @@ -116,14 +116,14 @@ sudo systemctl restart postgresql-16.service && psql -U postgres -d postgres -h Download installation package: ```bash -wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.rpm +wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm {:copy-code} ``` Go to the download repository and install ThingsBoard Edge service: ```bash -sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}pe.rpm +sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm {:copy-code} ``` diff --git a/application/src/main/data/json/edge/instructions/install/docker/instructions.md b/application/src/main/data/json/edge/instructions/install/docker/instructions.md index 22388933bb..675ccd6a96 100644 --- a/application/src/main/data/json/edge/instructions/install/docker/instructions.md +++ b/application/src/main/data/json/edge/instructions/install/docker/instructions.md @@ -24,7 +24,7 @@ Add the following lines to the yml file: services: mytbedge: restart: always - image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" + image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}" ports: - "8080:8080" - "1883:1883" diff --git a/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md b/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md index 47bca5a980..cb3c4d2c61 100644 --- a/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md +++ b/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md @@ -74,14 +74,14 @@ echo "CREATE DATABASE tb_edge;" | psql -U postgres -d postgres -h 127.0.0.1 -W Download the installation package: ```bash -wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.deb +wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb {:copy-code} ``` Go to the download repository and install ThingsBoard Edge service: ```bash -sudo dpkg -i tb-edge-${TB_EDGE_TAG}pe.deb +sudo dpkg -i tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb {:copy-code} ``` diff --git a/application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md b/application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md index 08039d2b4f..3007f841c7 100644 --- a/application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md +++ b/application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md @@ -1,14 +1,14 @@ -#### Upgrading to ${TB_EDGE_VERSION}EDGEPE +#### Upgrading to ${TB_EDGE_VERSION} ThingsBoard Edge package download: ```bash -wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.rpm +wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm {:copy-code} ``` Install package: ```bash -sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}pe.rpm +sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm {:copy-code} ``` diff --git a/application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md b/application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md index b2830cfa71..d72baab007 100644 --- a/application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md +++ b/application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md @@ -8,11 +8,11 @@ nano docker-compose.yml services: mytbedge: restart: always - image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" + image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}" ... ``` -Make sure your image is set to **tb-edge-pe:${TB_EDGE_VERSION}**. +Make sure your image is set to **${TB_EDGE_REPO}:${TB_EDGE_VERSION}**. Execute the following commands to up this docker compose directly: ```bash diff --git a/application/src/main/data/json/edge/instructions/upgrade/docker/upgrade_db.md b/application/src/main/data/json/edge/instructions/upgrade/docker/upgrade_db.md index 4786f9ac9d..84d16a1ee6 100644 --- a/application/src/main/data/json/edge/instructions/upgrade/docker/upgrade_db.md +++ b/application/src/main/data/json/edge/instructions/upgrade/docker/upgrade_db.md @@ -11,7 +11,7 @@ Add the following lines to the yml file: services: mytbedge: restart: on-failure - image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" + image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}" environment: SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/tb-edge volumes: diff --git a/application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md b/application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md index 5d9fdcc32c..158bd1b239 100644 --- a/application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md +++ b/application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md @@ -1,13 +1,13 @@ -#### Upgrading to ${TB_EDGE_VERSION}EDGEPE +#### Upgrading to ${TB_EDGE_VERSION} ThingsBoard Edge package download: ```bash -wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.deb +wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb {:copy-code} ``` Install package: ```bash -sudo dpkg -i tb-edge-${TB_EDGE_TAG}pe.deb +sudo dpkg -i tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb {:copy-code} ``` diff --git a/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeInstallInstructionsService.java b/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeInstallInstructionsService.java index 2ce51cc476..955a743262 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeInstallInstructionsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeInstallInstructionsService.java @@ -8,8 +8,10 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.TbVersionUtils; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeInstructions; +import org.thingsboard.server.dao.edge.EdgeEditionStyle; import org.thingsboard.server.dao.util.DeviceConnectivityUtil; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.install.InstallScripts; @@ -53,8 +55,10 @@ public class DefaultEdgeInstallInstructionsService extends BaseEdgeInstallUpgrad dockerInstallInstructions = dockerInstallInstructions.replace("${EXTRA_HOSTS}", ""); dockerInstallInstructions = dockerInstallInstructions.replace("${BASE_URL}", baseUrl); } - String edgeVersion = platformEdgeVersion.replace("-SNAPSHOT", "").replace("PE", ""); - dockerInstallInstructions = dockerInstallInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + "EDGEPE"); + String edgeVersion = TbVersionUtils.extractStartingDigits(platformEdgeVersion); + EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion); + dockerInstallInstructions = edition.replacePlaceholders(dockerInstallInstructions); + dockerInstallInstructions = dockerInstallInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + edition.getVersionSuffix()); dockerInstallInstructions = replacePlaceholders(dockerInstallInstructions, edge); return new EdgeInstructions(dockerInstallInstructions); } @@ -63,8 +67,9 @@ public class DefaultEdgeInstallInstructionsService extends BaseEdgeInstallUpgrad String ubuntuInstallInstructions = readFile(resolveFile(os, "instructions.md")); ubuntuInstallInstructions = replacePlaceholders(ubuntuInstallInstructions, edge); ubuntuInstallInstructions = ubuntuInstallInstructions.replace("${BASE_URL}", request.getServerName()); - String edgeVersion = platformEdgeVersion.replace("-SNAPSHOT", "").replace("PE", "pe"); - ubuntuInstallInstructions = ubuntuInstallInstructions.replace("${TB_EDGE_TAG}", getTagVersion(edgeVersion).replace("pe", "")); + String edgeVersion = TbVersionUtils.extractStartingDigits(platformEdgeVersion); + ubuntuInstallInstructions = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion).replacePlaceholders(ubuntuInstallInstructions); + ubuntuInstallInstructions = ubuntuInstallInstructions.replace("${TB_EDGE_TAG}", getTagVersion(edgeVersion)); return new EdgeInstructions(ubuntuInstallInstructions); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeUpgradeInstructionsService.java b/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeUpgradeInstructionsService.java index 2c94e5d112..165d418e2f 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeUpgradeInstructionsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeUpgradeInstructionsService.java @@ -15,6 +15,7 @@ import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.edge.EdgeEditionStyle; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.install.InstallScripts; @@ -83,6 +84,8 @@ public class DefaultEdgeUpgradeInstructionsService extends BaseEdgeInstallUpgrad StringBuilder result = new StringBuilder(readFile(resolveFile("docker", "upgrade_preparing.md"))); while (edgeUpgradeInfo.getNextEdgeVersion() != null && !platformEdgeVersion.equals(currentEdgeVersion)) { String edgeVersion = edgeUpgradeInfo.getNextEdgeVersion(); + EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion); + EdgeEditionStyle fromEdition = EdgeEditionStyle.getEdgeEditionStyle(currentEdgeVersion); String dockerUpgradeInstructions = readFile(resolveFile("docker", "instructions.md")); if (edgeUpgradeInfo.isRequiresUpdateDb()) { String upgradeDb = readFile(resolveFile("docker", "upgrade_db.md")); @@ -90,14 +93,16 @@ public class DefaultEdgeUpgradeInstructionsService extends BaseEdgeInstallUpgrad } else { dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${UPGRADE_DB}", ""); } - dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + "EDGEPE"); - dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${FROM_TB_EDGE_VERSION}", currentEdgeVersion + "EDGEPE"); + dockerUpgradeInstructions = edition.replacePlaceholders(dockerUpgradeInstructions); + dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + edition.getVersionSuffix()); + dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${FROM_TB_EDGE_VERSION}", currentEdgeVersion + fromEdition.getVersionSuffix()); currentEdgeVersion = edgeVersion; edgeUpgradeInfo = upgradeVersionHashMap.get(edgeUpgradeInfo.getNextEdgeVersion()); result.append(dockerUpgradeInstructions); } - String startService = readFile(resolveFile("docker", "start_service.md")); - startService = startService.replace("${TB_EDGE_VERSION}", currentEdgeVersion + "EDGEPE"); + EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(currentEdgeVersion); + String startService = edition.replacePlaceholders(readFile(resolveFile("docker", "start_service.md"))); + startService = startService.replace("${TB_EDGE_VERSION}", currentEdgeVersion + edition.getVersionSuffix()); result.append(startService); return new EdgeInstructions(result.toString()); } @@ -112,6 +117,7 @@ public class DefaultEdgeUpgradeInstructionsService extends BaseEdgeInstallUpgrad StringBuilder result = new StringBuilder(upgrade_preparing); while (edgeUpgradeInfo.getNextEdgeVersion() != null && !platformEdgeVersion.equals(currentEdgeVersion)) { String edgeVersion = edgeUpgradeInfo.getNextEdgeVersion(); + EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion); String linuxUpgradeInstructions = readFile(resolveFile(os, "instructions.md")); if (edgeUpgradeInfo.isRequiresUpdateDb()) { String upgradeDb = readFile(resolveFile("upgrade_db.md")); @@ -119,9 +125,10 @@ public class DefaultEdgeUpgradeInstructionsService extends BaseEdgeInstallUpgrad } else { linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${UPGRADE_DB}", ""); } + linuxUpgradeInstructions = edition.replacePlaceholders(linuxUpgradeInstructions); linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${TB_EDGE_TAG}", getTagVersion(edgeVersion)); linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${FROM_TB_EDGE_TAG}", getTagVersion(currentEdgeVersion)); - linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${TB_EDGE_VERSION}", edgeVersion); + linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + edition.getVersionSuffix()); linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${FROM_TB_EDGE_VERSION}", currentEdgeVersion); currentEdgeVersion = edgeVersion; edgeUpgradeInfo = upgradeVersionHashMap.get(edgeUpgradeInfo.getNextEdgeVersion()); diff --git a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java new file mode 100644 index 0000000000..178d22dfac --- /dev/null +++ b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java @@ -0,0 +1,26 @@ +package org.thingsboard.server.dao.edge; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.thingsboard.common.util.TbVersionUtils; + +@Getter +@RequiredArgsConstructor +public enum EdgeEditionStyle { + CE("tb-edge", "EDGE", ""), + PE("tb-edge-pe", "EDGEPE", "pe"); + + private final String dockerRepo; + private final String versionSuffix; + private final String packageSuffix; + + public static EdgeEditionStyle getEdgeEditionStyle(String edgeVersion) { + return TbVersionUtils.compare(edgeVersion, "4.4") > 0 ? CE : PE; + } + + public String replacePlaceholders(String instructions) { + return instructions + .replace("${TB_EDGE_REPO}", dockerRepo) + .replace("${TB_EDGE_PKG_SUFFIX}", packageSuffix); + } +} From e266a8ef4e888522033177a07103693b28dbfd5d Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 6 Oct 2026 13:07:42 +0200 Subject: [PATCH 02/10] Resolve edge template version suffix per edition and accept CE-style tb-edge image in agent apps --- .../template/AgentAppTemplateSyncService.java | 17 +++++++++++------ .../AgentAppTemplateSyncServiceTest.java | 19 ++++++++++++++++--- .../data/agent/AgentApplicationType.java | 5 +++-- .../data/agent/AgentApplicationTypeTest.java | 8 ++++++-- .../server/dao/edge/EdgeEditionStyle.java | 2 +- 5 files changed, 37 insertions(+), 14 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java index fd339ddb5f..9a70064ea8 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java @@ -24,6 +24,7 @@ import org.thingsboard.server.common.data.EdgeUpgradeMessageV2; import org.thingsboard.server.common.data.agent.AgentApplicationType; import org.thingsboard.server.common.data.agent.config.AgentAppConfigType; import org.thingsboard.server.common.data.util.CollectionsUtil; +import org.thingsboard.server.dao.edge.EdgeEditionStyle; import org.thingsboard.server.dao.sql.agent.AppTemplateRegistry; import org.thingsboard.server.queue.util.AfterStartUp; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -68,7 +69,6 @@ public class AgentAppTemplateSyncService { private static final int APP_TYPE_GROUP_NUM = 1; private static final int CONFIG_TYPE_GROUP_NUM = 2; private static final String REPO_KEY = "agent-app-templates"; - private static final String EDGE_IMAGE_VERSION_SUFFIX = "EDGEPE"; private static final Duration UPDATE_SERVER_CONNECT_TIMEOUT = Duration.ofSeconds(10); private static final Duration UPDATE_SERVER_READ_TIMEOUT = Duration.ofSeconds(30); @@ -169,8 +169,8 @@ public class AgentAppTemplateSyncService { private List resolveDescriptors(AgentApplicationType appType) { return switch (appType) { - case EDGE -> appendVersionSuffix(filterCurrentlySupportedVersions( - filterVersionsWithoutTemplates(edgeDescriptors(), minSupportedEdgeVersion, appType)), EDGE_IMAGE_VERSION_SUFFIX); + case EDGE -> appendEdgeVersionSuffix(filterCurrentlySupportedVersions( + filterVersionsWithoutTemplates(edgeDescriptors(), minSupportedEdgeVersion, appType))); case GATEWAY -> filterVersionsWithoutTemplates( buildDescriptors(gatewayVersionGraph(), "gatewayVersions", "nextGatewayVersion", false), minSupportedGatewayVersion, appType); @@ -178,18 +178,23 @@ public class AgentAppTemplateSyncService { }; } - static List appendVersionSuffix(List descriptors, String suffix) { + // edge image tags carry an edition suffix that depends on the version itself (e.g. 4.4.0EDGEPE vs 4.4.1EDGE) + static List appendEdgeVersionSuffix(List descriptors) { if (CollectionsUtil.isEmpty(descriptors)) { return descriptors; } return descriptors.stream() .map(d -> new AppVersionDescriptor( - d.getVersion() + suffix, - d.getNextVersion() == null ? null : d.getNextVersion() + suffix, + withEdgeVersionSuffix(d.getVersion()), + withEdgeVersionSuffix(d.getNextVersion()), d.isRequiresUpdateDb())) .collect(Collectors.toList()); } + private static String withEdgeVersionSuffix(String version) { + return version == null ? null : version + EdgeEditionStyle.getEdgeEditionStyle(version).getVersionSuffix(); + } + List filterCurrentlySupportedVersions(List descriptors) { if (CollectionsUtil.isEmpty(descriptors)) { return descriptors; diff --git a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java index 4f345aff4f..677c6e3baf 100644 --- a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java @@ -135,10 +135,10 @@ class AgentAppTemplateSyncServiceTest { } @Test - void appendVersionSuffixRewritesBothVersionAndNextVersion() { - List result = AgentAppTemplateSyncService.appendVersionSuffix(List.of( + void appendEdgeVersionSuffixRewritesBothVersionAndNextVersion() { + List result = AgentAppTemplateSyncService.appendEdgeVersionSuffix(List.of( new AppVersionDescriptor("4.1.0", "4.2.0", true), - new AppVersionDescriptor("4.2.0", null, false)), "EDGEPE"); + new AppVersionDescriptor("4.2.0", null, false))); assertThat(result).extracting(AppVersionDescriptor::getVersion) .containsExactly("4.1.0EDGEPE", "4.2.0EDGEPE"); @@ -146,4 +146,17 @@ class AgentAppTemplateSyncServiceTest { assertThat(result.get(0).isRequiresUpdateDb()).isTrue(); assertThat(result.get(1).getNextVersion()).isNull(); } + + @Test + void appendEdgeVersionSuffixSwitchesToCeStyleFrom441() { + List result = AgentAppTemplateSyncService.appendEdgeVersionSuffix(List.of( + new AppVersionDescriptor("4.4.0", "4.4.0.1", false), + new AppVersionDescriptor("4.4.0.1", "4.4.1", true), + new AppVersionDescriptor("4.4.1", null, false))); + + assertThat(result).extracting(AppVersionDescriptor::getVersion) + .containsExactly("4.4.0EDGEPE", "4.4.0.1EDGEPE", "4.4.1EDGE"); + assertThat(result).extracting(AppVersionDescriptor::getNextVersion) + .containsExactly("4.4.0.1EDGEPE", "4.4.1EDGE", null); + } } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/agent/AgentApplicationType.java b/common/data/src/main/java/org/thingsboard/server/common/data/agent/AgentApplicationType.java index eddc7da972..1e22b7ee44 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/agent/AgentApplicationType.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/agent/AgentApplicationType.java @@ -15,8 +15,9 @@ public enum AgentApplicationType { // GENERIC has no version graph; its single template is materialized and registered under this defaultVersion. GENERIC(null, "default", null, Collections.emptyList()), // the leading "(?:[^/\s]+/)*" accepts optional registry/namespace segments, so an image pulled through a - // private mirror still matches: patterns are applied with Matcher.matches() over the whole image reference - EDGE("(?:[^/\\s]+/)*thingsboard/tb-edge-pe:.+", null, EntityType.EDGE, + // private mirror still matches: patterns are applied with Matcher.matches() over the whole image reference; + // edge accepts both the CE-style "tb-edge" repo and the legacy "tb-edge-pe" one + EDGE("(?:[^/\\s]+/)*thingsboard/tb-edge(?:-pe)?:.+", null, EntityType.EDGE, List.of("CLOUD_ROUTING_KEY", "CLOUD_ROUTING_SECRET")), GATEWAY("(?:[^/\\s]+/)*thingsboard/tb-gateway:.+", null, EntityType.DEVICE, gatewayCredentialEnvKeys()); diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/agent/AgentApplicationTypeTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/agent/AgentApplicationTypeTest.java index 2be1697cfd..f9be8d8408 100644 --- a/common/data/src/test/java/org/thingsboard/server/common/data/agent/AgentApplicationTypeTest.java +++ b/common/data/src/test/java/org/thingsboard/server/common/data/agent/AgentApplicationTypeTest.java @@ -15,7 +15,9 @@ class AgentApplicationTypeTest { "thingsboard/tb-edge-pe:4.2.0", "registry.example.com/thingsboard/tb-edge-pe:4.2.0", "registry.example.com:5000/thingsboard/tb-edge-pe:4.2.0", - "my-mirror/proxy/thingsboard/tb-edge-pe:4.2.0" + "my-mirror/proxy/thingsboard/tb-edge-pe:4.2.0", + "thingsboard/tb-edge:4.5.0EDGE", + "registry.example.com/thingsboard/tb-edge:4.5.0EDGE" }) void edgePatternAcceptsDockerHubAndMirroredImages(String image) { assertThat(AgentApplicationType.EDGE.getMainImagePattern().matcher(image).matches()).isTrue(); @@ -33,8 +35,10 @@ class AgentApplicationTypeTest { @ParameterizedTest @ValueSource(strings = { "thingsboard/tb-edge-pe", - "thingsboard/tb-edge:4.2.0", + "thingsboard/tb-edge", + "thingsboard/tb-edge-foo:4.2.0", "someone/tb-edge-pe:4.2.0", + "someone/tb-edge:4.5.0EDGE", "registry.example.com/thingsboard/tb-gateway:3.8.0" }) void edgePatternStillRejectsAnythingButTheEdgeImage(String image) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java index 178d22dfac..382aa1ced1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java +++ b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java @@ -15,7 +15,7 @@ public enum EdgeEditionStyle { private final String packageSuffix; public static EdgeEditionStyle getEdgeEditionStyle(String edgeVersion) { - return TbVersionUtils.compare(edgeVersion, "4.4") > 0 ? CE : PE; + return TbVersionUtils.compare(edgeVersion, "4.4.1") >= 0 ? CE : PE; } public String replacePlaceholders(String instructions) { From 47376c020bd7f51de9f416bc2723550fe1dd252e Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 6 Oct 2026 13:27:15 +0200 Subject: [PATCH 03/10] Fall back to the closest lower version subfolder when resolving agent app compose files --- .../template/AppTemplateMaterializer.java | 81 ++++++++++++------- .../template/AppTemplateMaterializerTest.java | 51 ++++++++++++ 2 files changed, 104 insertions(+), 28 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java index f492bba953..41ba5f7b4d 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java @@ -19,7 +19,6 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.agent.StepLinkedListUtils; import java.util.ArrayList; -import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; @@ -167,9 +166,10 @@ public class AppTemplateMaterializer { /** * Load the compose body for {@code path}, preferring the most specific version subfolder that actually exists in - * the repo. For version {@code 4.3.1.2} with a base {@code composeLine} of {@code 4.3}, this tries - * {@code compose/edge/4.3/4.3.1/4.3.1.2/…}, then {@code …/4.3/4.3.1/…}, then the base {@code …/4.3/…}. Falls through - * to an error (so the version is skipped, as before) only when no candidate exists. + * the repo. For version {@code 4.4.3} with a base {@code composeLine} of {@code 4.4}, this tries + * {@code compose/edge/4.4/4.4.3/…}, then the lower siblings {@code …/4.4/4.4.2/…}, {@code …/4.4/4.4.1/…}, + * {@code …/4.4/4.4.0/…}, then the base {@code …/4.4/…}. Falls through to an error (so the version is skipped, + * as before) only when no candidate exists. */ private JsonNode loadMostSpecificCompose(String path, Map vars, Function composeLoader) { List candidates = composePathCandidates(path, vars); @@ -183,38 +183,63 @@ public class AppTemplateMaterializer { } /** - * Candidate compose paths, most specific first, obtained by expanding the {@code composeLine} folder segment into - * progressively deeper version subfolders (e.g. {@code 4.3} -> {@code 4.3/4.3.1} -> {@code 4.3/4.3.1/4.3.1.2}). + * Candidate compose paths, most specific first. The {@code composeLine} folder of {@code path} is swapped for the + * nested version subfolders of {@link #subfolderVersions}, ending with {@code path} itself, e.g. for version + * {@code 4.4.3}: {@code …/4.4/4.4.3/…}, {@code …/4.4/4.4.2/…}, {@code …/4.4/4.4.1/…}, {@code …/4.4/4.4.0/…}, + * {@code …/4.4/…}. */ - private List composePathCandidates(String path, Map vars) { - Object lineObj = vars.get("composeLine"); - Object versionObj = vars.get("version"); - if (lineObj == null || versionObj == null) { + static List composePathCandidates(String path, Map vars) { + Object line = vars.get("composeLine"); + Object version = vars.get("version"); + if (line == null || version == null) { return List.of(path); } - String line = lineObj.toString(); - String[] parts = TbVersionUtils.extractStartingDigits(versionObj.toString()).split("\\."); - int baseFolderDepth = line.split("\\.").length; + String lineFolder = "/" + line + "/"; + List candidates = new ArrayList<>(); + for (String subfolderVersion : subfolderVersions(line.toString(), TbVersionUtils.extractStartingDigits(version.toString()))) { + String subfolder = "/" + nestedFolder(line.toString(), subfolderVersion) + "/"; + candidates.add(path.replaceFirst(Pattern.quote(lineFolder), Matcher.quoteReplacement(subfolder))); + } + candidates.add(path); + return candidates; + } - // Dotted prefixes from the composeLine depth up to the full numeric version, e.g. ["4.3","4.3.1","4.3.1.2"]. - List dottedPrefixes = new ArrayList<>(); - for (int i = baseFolderDepth; i <= parts.length; i++) { - dottedPrefixes.add(String.join(".", Arrays.copyOfRange(parts, 0, i))); + /** + * Versions whose subfolder may hold the compose for {@code version}, most specific first. A subfolder applies to + * its own version and every later sibling until a newer one exists, so each level is followed by its lower + * siblings: {@code 4.4.1.2} -> {@code 4.4.1.2, 4.4.1.1, 4.4.1.0, 4.4.1, 4.4.0}. Empty when the version is the line + * itself or does not belong to it. + */ + private static List subfolderVersions(String line, String version) { + List versions = new ArrayList<>(); + if (!version.startsWith(line + ".")) { + return versions; } - // Guard: version must share the composeLine prefix; otherwise just use the base path. - if (dottedPrefixes.isEmpty() || !dottedPrefixes.get(0).equals(line)) { - return List.of(path); + for (String level = version; !level.equals(line); level = parentVersion(level)) { + String parent = parentVersion(level); + for (int sibling = lastSegment(level); sibling >= 0; sibling--) { + versions.add(parent + "." + sibling); + } } + return versions; + } - List candidates = new ArrayList<>(); - for (int depth = dottedPrefixes.size(); depth >= 1; depth--) { - String nestedLine = String.join("/", dottedPrefixes.subList(0, depth)); - candidates.add(line.equals(nestedLine) - ? path - : path.replaceFirst("/" + Pattern.quote(line) + "/", - "/" + Matcher.quoteReplacement(nestedLine) + "/")); + // Nested folder of a version under its line, e.g. line 4.4 and version 4.4.1.2 -> "4.4/4.4.1/4.4.1.2". + private static String nestedFolder(String line, String version) { + List folders = new ArrayList<>(); + for (String level = version; !level.equals(line); level = parentVersion(level)) { + folders.add(0, level); } - return candidates; + folders.add(0, line); + return String.join("/", folders); + } + + private static String parentVersion(String version) { + return version.substring(0, version.lastIndexOf('.')); + } + + private static int lastSegment(String version) { + return Integer.parseInt(version.substring(version.lastIndexOf('.') + 1)); } private Map buildVars(AppVersionDescriptor d) { diff --git a/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java b/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java new file mode 100644 index 0000000000..7c8a808d52 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.agent.template; + +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class AppTemplateMaterializerTest { + + private static final String PATH = "compose/edge/4.4/kafka.yml"; + + @Test + void patchVersionFallsBackThroughLowerPatchFoldersToTheLine() { + assertThat(AppTemplateMaterializer.composePathCandidates(PATH, vars("4.4", "4.4.3EDGE"))).containsExactly( + "compose/edge/4.4/4.4.3/kafka.yml", + "compose/edge/4.4/4.4.2/kafka.yml", + "compose/edge/4.4/4.4.1/kafka.yml", + "compose/edge/4.4/4.4.0/kafka.yml", + "compose/edge/4.4/kafka.yml"); + } + + @Test + void hotfixVersionFallsBackThroughLowerHotfixesThenLowerPatches() { + assertThat(AppTemplateMaterializer.composePathCandidates(PATH, vars("4.4", "4.4.1.2EDGE"))).containsExactly( + "compose/edge/4.4/4.4.1/4.4.1.2/kafka.yml", + "compose/edge/4.4/4.4.1/4.4.1.1/kafka.yml", + "compose/edge/4.4/4.4.1/4.4.1.0/kafka.yml", + "compose/edge/4.4/4.4.1/kafka.yml", + "compose/edge/4.4/4.4.0/kafka.yml", + "compose/edge/4.4/kafka.yml"); + } + + @Test + void lineVersionUsesTheLineFolderOnly() { + assertThat(AppTemplateMaterializer.composePathCandidates("compose/gateway/3.8/compose.yml", vars("3.8", "3.8-stable"))) + .containsExactly("compose/gateway/3.8/compose.yml"); + } + + @Test + void versionOutsideTheLineUsesThePathAsIs() { + assertThat(AppTemplateMaterializer.composePathCandidates(PATH, vars("4.4", "4.5.0EDGE"))) + .containsExactly(PATH); + } + + private static Map vars(String composeLine, String version) { + return Map.of("composeLine", composeLine, "version", version); + } +} From 56406129c8dc6d9e11a94a203013951c3ec27697 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 6 Oct 2026 15:16:22 +0200 Subject: [PATCH 04/10] Add license header to EdgeEditionStyle --- .../java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java index 382aa1ced1..10e85b6db1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java +++ b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.dao.edge; import lombok.Getter; From d020d4c8c910caa644e34754e92f1f83e7e72d9f Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 6 Oct 2026 15:16:22 +0200 Subject: [PATCH 05/10] Override agent app templates from since/ folders and expose edge image repo vars --- .../template/AgentAppTemplateSyncService.java | 32 +++++++++++- .../template/AppTemplateMaterializer.java | 8 +++ .../AgentAppTemplateSyncServiceTest.java | 50 +++++++++++++++++++ 3 files changed, 88 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java index 9a70064ea8..a7bb356a23 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java @@ -40,8 +40,10 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -69,6 +71,9 @@ public class AgentAppTemplateSyncService { private static final int APP_TYPE_GROUP_NUM = 1; private static final int CONFIG_TYPE_GROUP_NUM = 2; private static final String REPO_KEY = "agent-app-templates"; + // /since// holds templates that replace the same-named base ones from that platform version on + private static final String SINCE_DIR = "since"; + private static final Pattern SINCE_VERSION_PATTERN = Pattern.compile("\\d+(\\.\\d+)*"); private static final Duration UPDATE_SERVER_CONNECT_TIMEOUT = Duration.ofSeconds(10); private static final Duration UPDATE_SERVER_READ_TIMEOUT = Duration.ofSeconds(30); @@ -147,12 +152,35 @@ public class AgentAppTemplateSyncService { return new RestTemplate(factory); } - private List getTemplateFiles() { - return gitSyncService.listFiles(REPO_KEY, basePath, 1, FileType.FILE).stream() + /** + * Base templates overridden per file name by {@code since//} ones, taking the newest folder whose version + * is not above the platform version. Servers older than a {@code since} folder only list the base folder, so the + * templates there are free to rely on newer materialization variables. + */ + List getTemplateFiles() { + String platform = TbVersionUtils.extractStartingDigits(projectInfo.getProjectVersion()); + Map byName = new LinkedHashMap<>(); + listTemplateFiles(basePath, 1).forEach(file -> byName.put(file.name(), file)); + listTemplateFiles(basePath + "/" + SINCE_DIR, 3).stream() + .filter(file -> RegexUtils.matches(sinceVersion(file), SINCE_VERSION_PATTERN)) + .filter(file -> TbVersionUtils.compare(sinceVersion(file), platform) <= 0) + .sorted(Comparator.comparing(AgentAppTemplateSyncService::sinceVersion, TbVersionUtils::compare)) + .forEach(file -> byName.put(file.name(), file)); + return new ArrayList<>(byName.values()); + } + + private List listTemplateFiles(String path, int depth) { + return gitSyncService.listFiles(REPO_KEY, path, depth, FileType.FILE).stream() .filter(file -> RegexUtils.matches(file.name(), TEMPLATE_FILE_PATTERN)) .collect(Collectors.toList()); } + // Name of the folder holding the file, e.g. templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json -> 4.4.1 + private static String sinceVersion(RepoFile file) { + String folder = file.path().substring(0, file.path().lastIndexOf('/')); + return folder.substring(folder.lastIndexOf('/') + 1); + } + private Function composeLoader() { // Returns null when the file is absent so the materializer can probe more/less specific // version subfolders (e.g. compose/edge/4.3/4.3.1 before compose/edge/4.3) and pick the closest match. diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java index 41ba5f7b4d..70acc694d9 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java @@ -17,6 +17,7 @@ import org.thingsboard.server.common.data.agent.step.ComposeTypeChoiceStep; import org.thingsboard.server.common.data.agent.template.AgentAppTemplate; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.agent.StepLinkedListUtils; +import org.thingsboard.server.dao.edge.EdgeEditionStyle; import java.util.ArrayList; import java.util.Comparator; @@ -234,6 +235,10 @@ public class AppTemplateMaterializer { return String.join("/", folders); } + private static String edgeRepo(String version) { + return version == null ? null : EdgeEditionStyle.getEdgeEditionStyle(version).getDockerRepo(); + } + private static String parentVersion(String version) { return version.substring(0, version.lastIndexOf('.')); } @@ -251,6 +256,9 @@ public class AppTemplateMaterializer { vars.put("nextVersion", d.getNextVersion()); vars.put("nextEdgeVersion", d.getNextVersion()); vars.put("nextGatewayVersion", d.getNextVersion()); + // edge image repo per version, as CE-style versions are published under tb-edge instead of tb-edge-pe + vars.put("edgeRepo", edgeRepo(d.getVersion())); + vars.put("nextEdgeRepo", edgeRepo(d.getNextVersion())); vars.put("composeLine", composeLine(d.getVersion())); vars.put("requiresUpdateDb", d.isRequiresUpdateDb()); return vars; diff --git a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java index 677c6e3baf..35cbc59e9d 100644 --- a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java @@ -8,11 +8,14 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.server.common.data.agent.AgentApplicationType; import org.thingsboard.server.dao.sql.agent.AppTemplateRegistry; import org.thingsboard.server.service.agent.template.AppTemplateMaterializer.AppVersionDescriptor; import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.sync.GitSyncService; +import org.thingsboard.server.service.sync.vc.GitRepository.FileType; +import org.thingsboard.server.service.sync.vc.GitRepository.RepoFile; import java.util.Arrays; import java.util.List; @@ -159,4 +162,51 @@ class AgentAppTemplateSyncServiceTest { assertThat(result).extracting(AppVersionDescriptor::getNextVersion) .containsExactly("4.4.0.1EDGEPE", "4.4.1EDGE", null); } + + @Test + void baseTemplatesAreUsedBelowEverySinceFolder() { + AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.0PE"); + + assertThat(service.getTemplateFiles()).extracting(RepoFile::path).containsExactlyInAnyOrder( + "templates/template-EDGE-DOCKER_COMPOSE.json", + "templates/template-GATEWAY-DOCKER_COMPOSE.json"); + } + + @Test + void sinceFolderReplacesOnlyTheTemplatesItContains() { + AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.1PE-SNAPSHOT"); + + assertThat(service.getTemplateFiles()).extracting(RepoFile::path).containsExactlyInAnyOrder( + "templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json", + "templates/template-GATEWAY-DOCKER_COMPOSE.json"); + } + + @Test + void newestApplicableSinceFolderWinsPerTemplate() { + AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.10.0"); + + assertThat(service.getTemplateFiles()).extracting(RepoFile::path).containsExactlyInAnyOrder( + "templates/since/4.9/template-EDGE-DOCKER_COMPOSE.json", + "templates/since/4.5/template-GATEWAY-DOCKER_COMPOSE.json"); + } + + private AgentAppTemplateSyncService serviceWithTemplateFiles(String platformVersion) { + AgentAppTemplateSyncService service = newService(platformVersion); + ReflectionTestUtils.setField(service, "basePath", "templates"); + when(gitSyncService.listFiles("agent-app-templates", "templates", 1, FileType.FILE)).thenReturn(List.of( + file("templates/template-EDGE-DOCKER_COMPOSE.json"), + file("templates/template-GATEWAY-DOCKER_COMPOSE.json"), + file("templates/README.md"))); + when(gitSyncService.listFiles("agent-app-templates", "templates/since", 3, FileType.FILE)).thenReturn(List.of( + file("templates/since/4.9/template-EDGE-DOCKER_COMPOSE.json"), + file("templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json"), + file("templates/since/4.5/template-GATEWAY-DOCKER_COMPOSE.json"), + file("templates/since/4.11/template-GATEWAY-DOCKER_COMPOSE.json"), + file("templates/since/draft/template-EDGE-DOCKER_COMPOSE.json"))); + return service; + } + + private static RepoFile file(String path) { + return new RepoFile(path, path.substring(path.lastIndexOf('/') + 1), FileType.FILE); + } } From 7ebe927566757d2ee3c1cbde426cc4334860c109 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 6 Oct 2026 17:23:47 +0200 Subject: [PATCH 06/10] Move CE-style edge cutoff to 4.4.0.1 and resolve agent app compose from flat version folders --- .../template/AgentAppTemplateSyncService.java | 35 ++++--- .../template/AppTemplateMaterializer.java | 94 ++++++------------- .../agent/template/VersionFolders.java | 32 +++++++ .../AgentAppTemplateSyncServiceTest.java | 24 +++-- .../template/AppTemplateMaterializerTest.java | 58 +++++++----- .../server/dao/edge/EdgeEditionStyle.java | 2 +- 6 files changed, 137 insertions(+), 108 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java index a7bb356a23..56cb5d5e62 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java @@ -40,7 +40,7 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; @@ -73,7 +73,6 @@ public class AgentAppTemplateSyncService { private static final String REPO_KEY = "agent-app-templates"; // /since// holds templates that replace the same-named base ones from that platform version on private static final String SINCE_DIR = "since"; - private static final Pattern SINCE_VERSION_PATTERN = Pattern.compile("\\d+(\\.\\d+)*"); private static final Duration UPDATE_SERVER_CONNECT_TIMEOUT = Duration.ofSeconds(10); private static final Duration UPDATE_SERVER_READ_TIMEOUT = Duration.ofSeconds(30); @@ -130,7 +129,7 @@ public class AgentAppTemplateSyncService { continue; } MaterializationResult result = materializer.materialize( - rawTemplate, appType, configType, descriptors, composeLoader()); + rawTemplate, appType, configType, descriptors, composeLoader(), folderLister()); if (result.getByVersion().isEmpty()) { log.warn("Materialized no versions for {}-{} (the version graph is empty or unreachable); " + "keeping the previously registered templates", appType, configType); @@ -159,28 +158,40 @@ public class AgentAppTemplateSyncService { */ List getTemplateFiles() { String platform = TbVersionUtils.extractStartingDigits(projectInfo.getProjectVersion()); + Map> sinceFilesByVersion = listTemplateFiles(basePath + "/" + SINCE_DIR, 2).stream() + .collect(Collectors.groupingBy(AgentAppTemplateSyncService::sinceVersion)); Map byName = new LinkedHashMap<>(); - listTemplateFiles(basePath, 1).forEach(file -> byName.put(file.name(), file)); - listTemplateFiles(basePath + "/" + SINCE_DIR, 3).stream() - .filter(file -> RegexUtils.matches(sinceVersion(file), SINCE_VERSION_PATTERN)) - .filter(file -> TbVersionUtils.compare(sinceVersion(file), platform) <= 0) - .sorted(Comparator.comparing(AgentAppTemplateSyncService::sinceVersion, TbVersionUtils::compare)) - .forEach(file -> byName.put(file.name(), file)); + for (String version : VersionFolders.applicableTo(sinceFilesByVersion.keySet(), platform)) { + sinceFilesByVersion.get(version).forEach(file -> byName.putIfAbsent(file.name(), file)); + } + listTemplateFiles(basePath, 1).forEach(file -> byName.putIfAbsent(file.name(), file)); return new ArrayList<>(byName.values()); } - - private List listTemplateFiles(String path, int depth) { - return gitSyncService.listFiles(REPO_KEY, path, depth, FileType.FILE).stream() + // Template files the given number of folders below path + private List listTemplateFiles(String path, int levels) { + return gitSyncService.listFiles(REPO_KEY, path, depthBelow(path, levels), FileType.FILE).stream() .filter(file -> RegexUtils.matches(file.name(), TEMPLATE_FILE_PATTERN)) .collect(Collectors.toList()); } // Name of the folder holding the file, e.g. templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json -> 4.4.1 + // Tree depth of the entries the given number of folders below path (root entries are at depth 0) + private static int depthBelow(String path, int levels) { + return path.split("/").length - 1 + levels; + } + private static String sinceVersion(RepoFile file) { String folder = file.path().substring(0, file.path().lastIndexOf('/')); return folder.substring(folder.lastIndexOf('/') + 1); } + // Names of the folders directly under a repo path, cached per template since every version lists the same folders + private Function> folderLister() { + Map> cache = new HashMap<>(); + return path -> cache.computeIfAbsent(path, p -> gitSyncService.listFiles(REPO_KEY, p, depthBelow(p, 1), FileType.DIRECTORY) + .stream().map(RepoFile::name).toList()); + } + private Function composeLoader() { // Returns null when the file is absent so the materializer can probe more/less specific // version subfolders (e.g. compose/edge/4.3/4.3.1 before compose/edge/4.3) and pick the closest match. diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java index 70acc694d9..294b41f6b2 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java @@ -19,7 +19,6 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.agent.StepLinkedListUtils; import org.thingsboard.server.dao.edge.EdgeEditionStyle; -import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; @@ -69,7 +68,8 @@ public class AppTemplateMaterializer { AgentApplicationType appType, AgentAppConfigType configType, List descriptors, - Function composeLoader) { + Function composeLoader, + Function> folderLister) { Map byVersion = new LinkedHashMap<>(); AgentAppTemplate latest = null; @@ -81,7 +81,7 @@ public class AppTemplateMaterializer { try { Map vars = buildVars(d); AgentAppTemplate template = materializeOne(rawTemplate, appType, configType, - d.getVersion(), d.getNextVersion(), vars, composeLoader); + d.getVersion(), d.getNextVersion(), vars, composeLoader, folderLister); byVersion.put(d.getVersion(), template); if (d.getNextVersion() == null) { latest = template; @@ -115,7 +115,8 @@ public class AppTemplateMaterializer { String version, String nextVersion, Map vars, - Function composeLoader) { + Function composeLoader, + Function> folderLister) { JsonNode substituted = TemplateVarSubstitutor.substitute(rawTemplate, vars); AgentAppTemplate template = JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER @@ -127,7 +128,7 @@ public class AppTemplateMaterializer { template.setCurrentVersion(version); template.setNextVersion(nextVersion); - resolveComposeTemplates(template.getStartSteps(), vars, composeLoader); + resolveComposeTemplates(template.getStartSteps(), vars, composeLoader, folderLister); Predicate disabled = step -> step.getCondition() != null && !truthy(vars.get(step.getCondition())); @@ -140,7 +141,8 @@ public class AppTemplateMaterializer { } private void resolveComposeTemplates(List steps, Map vars, - Function composeLoader) { + Function composeLoader, + Function> folderLister) { if (steps == null) { return; } @@ -154,7 +156,7 @@ public class AppTemplateMaterializer { if (value != null && value.isTextual()) { String path = value.asText(); if (path.endsWith(".yml") || path.endsWith(".yaml")) { - JsonNode compose = loadMostSpecificCompose(path, vars, composeLoader); + JsonNode compose = loadMostSpecificCompose(path, vars, composeLoader, folderLister); resolved.put(entry.getKey(), TemplateVarSubstitutor.substitute(compose, vars)); continue; } @@ -166,14 +168,15 @@ public class AppTemplateMaterializer { } /** - * Load the compose body for {@code path}, preferring the most specific version subfolder that actually exists in - * the repo. For version {@code 4.4.3} with a base {@code composeLine} of {@code 4.4}, this tries - * {@code compose/edge/4.4/4.4.3/…}, then the lower siblings {@code …/4.4/4.4.2/…}, {@code …/4.4/4.4.1/…}, - * {@code …/4.4/4.4.0/…}, then the base {@code …/4.4/…}. Falls through to an error (so the version is skipped, - * as before) only when no candidate exists. + * Load the compose body for {@code path}, taking the file from the newest version folder that has it. For version + * {@code 4.4.1} and {@code compose/edge/4.4/kafka.yml} with folders {@code 4.3, 4.4, 4.4.0.1} under + * {@code compose/edge}, this tries {@code compose/edge/4.4.0.1/kafka.yml}, then {@code compose/edge/4.4/kafka.yml}, + * then {@code compose/edge/4.3/kafka.yml}. Falls through to an error (so the version is skipped) only when no + * candidate exists. */ - private JsonNode loadMostSpecificCompose(String path, Map vars, Function composeLoader) { - List candidates = composePathCandidates(path, vars); + private JsonNode loadMostSpecificCompose(String path, Map vars, Function composeLoader, + Function> folderLister) { + List candidates = composePathCandidates(path, vars, folderLister); for (String candidate : candidates) { JsonNode compose = composeLoader.apply(candidate); if (compose != null) { @@ -184,69 +187,28 @@ public class AppTemplateMaterializer { } /** - * Candidate compose paths, most specific first. The {@code composeLine} folder of {@code path} is swapped for the - * nested version subfolders of {@link #subfolderVersions}, ending with {@code path} itself, e.g. for version - * {@code 4.4.3}: {@code …/4.4/4.4.3/…}, {@code …/4.4/4.4.2/…}, {@code …/4.4/4.4.1/…}, {@code …/4.4/4.4.0/…}, - * {@code …/4.4/…}. + * Candidate compose paths, newest first: the {@code composeLine} folder of {@code path} is swapped for each sibling + * version folder that applies to the version (see {@link VersionFolders}). Paths without a {@code composeLine} + * folder (e.g. {@code compose/generic/default/...}) are used as-is. */ - static List composePathCandidates(String path, Map vars) { + static List composePathCandidates(String path, Map vars, Function> folderLister) { Object line = vars.get("composeLine"); Object version = vars.get("version"); - if (line == null || version == null) { - return List.of(path); - } String lineFolder = "/" + line + "/"; - List candidates = new ArrayList<>(); - for (String subfolderVersion : subfolderVersions(line.toString(), TbVersionUtils.extractStartingDigits(version.toString()))) { - String subfolder = "/" + nestedFolder(line.toString(), subfolderVersion) + "/"; - candidates.add(path.replaceFirst(Pattern.quote(lineFolder), Matcher.quoteReplacement(subfolder))); - } - candidates.add(path); - return candidates; - } - - /** - * Versions whose subfolder may hold the compose for {@code version}, most specific first. A subfolder applies to - * its own version and every later sibling until a newer one exists, so each level is followed by its lower - * siblings: {@code 4.4.1.2} -> {@code 4.4.1.2, 4.4.1.1, 4.4.1.0, 4.4.1, 4.4.0}. Empty when the version is the line - * itself or does not belong to it. - */ - private static List subfolderVersions(String line, String version) { - List versions = new ArrayList<>(); - if (!version.startsWith(line + ".")) { - return versions; - } - for (String level = version; !level.equals(line); level = parentVersion(level)) { - String parent = parentVersion(level); - for (int sibling = lastSegment(level); sibling >= 0; sibling--) { - versions.add(parent + "." + sibling); - } - } - return versions; - } - - // Nested folder of a version under its line, e.g. line 4.4 and version 4.4.1.2 -> "4.4/4.4.1/4.4.1.2". - private static String nestedFolder(String line, String version) { - List folders = new ArrayList<>(); - for (String level = version; !level.equals(line); level = parentVersion(level)) { - folders.add(0, level); + if (line == null || version == null || !path.contains(lineFolder)) { + return List.of(path); } - folders.add(0, line); - return String.join("/", folders); + String parent = path.substring(0, path.indexOf(lineFolder)); + String file = path.substring(path.indexOf(lineFolder) + lineFolder.length()); + List folders = VersionFolders.applicableTo(folderLister.apply(parent), + TbVersionUtils.extractStartingDigits(version.toString())); + return folders.isEmpty() ? List.of(path) : folders.stream().map(folder -> parent + "/" + folder + "/" + file).toList(); } private static String edgeRepo(String version) { return version == null ? null : EdgeEditionStyle.getEdgeEditionStyle(version).getDockerRepo(); } - private static String parentVersion(String version) { - return version.substring(0, version.lastIndexOf('.')); - } - - private static int lastSegment(String version) { - return Integer.parseInt(version.substring(version.lastIndexOf('.') + 1)); - } - private Map buildVars(AppVersionDescriptor d) { Map vars = new HashMap<>(); // App-agnostic + per-app aliases, so the same materializer serves EDGE/GATEWAY templates. diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java b/application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java new file mode 100644 index 0000000000..7abcc2eb36 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.agent.template; + +import org.thingsboard.common.util.TbVersionUtils; + +import java.util.Collection; +import java.util.List; +import java.util.regex.Pattern; + +/** + * Version-named folders of the templates repo (e.g. {@code templates/since/4.4.0.1}, {@code compose/edge/4.4}): a + * folder applies to its own version and every later one, until a newer folder exists. + */ +final class VersionFolders { + + private static final Pattern VERSION = Pattern.compile("\\d+(\\.\\d+)*"); + + private VersionFolders() { + } + + /** + * The folder names that are plain versions not above {@code version}, newest first; other names are ignored. + */ + static List applicableTo(Collection folders, String version) { + return folders.stream() + .filter(folder -> VERSION.matcher(folder).matches()) + .filter(folder -> TbVersionUtils.compare(folder, version) <= 0) + .sorted((a, b) -> TbVersionUtils.compare(b, a)) + .toList(); + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java index 35cbc59e9d..0c389ec57d 100644 --- a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java @@ -151,16 +151,17 @@ class AgentAppTemplateSyncServiceTest { } @Test - void appendEdgeVersionSuffixSwitchesToCeStyleFrom441() { + void appendEdgeVersionSuffixSwitchesToCeStyleFrom4401() { List result = AgentAppTemplateSyncService.appendEdgeVersionSuffix(List.of( + new AppVersionDescriptor("4.3.1.6", "4.4.0", true), new AppVersionDescriptor("4.4.0", "4.4.0.1", false), - new AppVersionDescriptor("4.4.0.1", "4.4.1", true), + new AppVersionDescriptor("4.4.0.1", "4.4.1", false), new AppVersionDescriptor("4.4.1", null, false))); assertThat(result).extracting(AppVersionDescriptor::getVersion) - .containsExactly("4.4.0EDGEPE", "4.4.0.1EDGEPE", "4.4.1EDGE"); + .containsExactly("4.3.1.6EDGEPE", "4.4.0EDGEPE", "4.4.0.1EDGE", "4.4.1EDGE"); assertThat(result).extracting(AppVersionDescriptor::getNextVersion) - .containsExactly("4.4.0.1EDGEPE", "4.4.1EDGE", null); + .containsExactly("4.4.0EDGEPE", "4.4.0.1EDGE", "4.4.1EDGE", null); } @Test @@ -174,10 +175,19 @@ class AgentAppTemplateSyncServiceTest { @Test void sinceFolderReplacesOnlyTheTemplatesItContains() { - AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.1PE-SNAPSHOT"); + AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.0.1PE-SNAPSHOT"); assertThat(service.getTemplateFiles()).extracting(RepoFile::path).containsExactlyInAnyOrder( - "templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json", + "templates/since/4.4.0.1/template-EDGE-DOCKER_COMPOSE.json", + "templates/template-GATEWAY-DOCKER_COMPOSE.json"); + } + + @Test + void versionWithoutItsOwnSinceFolderUsesTheNewestLowerOne() { + AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.1"); + + assertThat(service.getTemplateFiles()).extracting(RepoFile::path).containsExactlyInAnyOrder( + "templates/since/4.4.0.1/template-EDGE-DOCKER_COMPOSE.json", "templates/template-GATEWAY-DOCKER_COMPOSE.json"); } @@ -199,7 +209,7 @@ class AgentAppTemplateSyncServiceTest { file("templates/README.md"))); when(gitSyncService.listFiles("agent-app-templates", "templates/since", 3, FileType.FILE)).thenReturn(List.of( file("templates/since/4.9/template-EDGE-DOCKER_COMPOSE.json"), - file("templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json"), + file("templates/since/4.4.0.1/template-EDGE-DOCKER_COMPOSE.json"), file("templates/since/4.5/template-GATEWAY-DOCKER_COMPOSE.json"), file("templates/since/4.11/template-GATEWAY-DOCKER_COMPOSE.json"), file("templates/since/draft/template-EDGE-DOCKER_COMPOSE.json"))); diff --git a/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java b/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java index 7c8a808d52..5e432af38d 100644 --- a/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java +++ b/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java @@ -4,48 +4,62 @@ package org.thingsboard.server.service.agent.template; import org.junit.jupiter.api.Test; +import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; class AppTemplateMaterializerTest { - private static final String PATH = "compose/edge/4.4/kafka.yml"; + private static final Function> EDGE_FOLDERS = parent -> parent.equals("compose/edge") + ? List.of("3.9", "4.3", "4.4", "4.4.0.1", "4.10", "latest") + : List.of(); @Test - void patchVersionFallsBackThroughLowerPatchFoldersToTheLine() { - assertThat(AppTemplateMaterializer.composePathCandidates(PATH, vars("4.4", "4.4.3EDGE"))).containsExactly( - "compose/edge/4.4/4.4.3/kafka.yml", - "compose/edge/4.4/4.4.2/kafka.yml", - "compose/edge/4.4/4.4.1/kafka.yml", - "compose/edge/4.4/4.4.0/kafka.yml", + void lineVersionUsesItsLineFolderThenOlderOnes() { + assertThat(candidates("compose/edge/4.4/kafka.yml", "4.4", "4.4.0EDGEPE")).containsExactly( + "compose/edge/4.4/kafka.yml", + "compose/edge/4.3/kafka.yml", + "compose/edge/3.9/kafka.yml"); + } + + @Test + void versionWithItsOwnFolderUsesItFirst() { + assertThat(candidates("compose/edge/4.4/kafka.yml", "4.4", "4.4.0.1EDGE")).startsWith( + "compose/edge/4.4.0.1/kafka.yml", "compose/edge/4.4/kafka.yml"); } @Test - void hotfixVersionFallsBackThroughLowerHotfixesThenLowerPatches() { - assertThat(AppTemplateMaterializer.composePathCandidates(PATH, vars("4.4", "4.4.1.2EDGE"))).containsExactly( - "compose/edge/4.4/4.4.1/4.4.1.2/kafka.yml", - "compose/edge/4.4/4.4.1/4.4.1.1/kafka.yml", - "compose/edge/4.4/4.4.1/4.4.1.0/kafka.yml", - "compose/edge/4.4/4.4.1/kafka.yml", - "compose/edge/4.4/4.4.0/kafka.yml", + void versionWithoutItsOwnFolderFallsBackToTheNewestLowerOne() { + assertThat(candidates("compose/edge/4.4/kafka.yml", "4.4", "4.4.1EDGE")).startsWith( + "compose/edge/4.4.0.1/kafka.yml", "compose/edge/4.4/kafka.yml"); + assertThat(candidates("compose/edge/4.5/kafka.yml", "4.5", "4.5.0EDGE")).startsWith( + "compose/edge/4.4.0.1/kafka.yml"); } @Test - void lineVersionUsesTheLineFolderOnly() { - assertThat(AppTemplateMaterializer.composePathCandidates("compose/gateway/3.8/compose.yml", vars("3.8", "3.8-stable"))) - .containsExactly("compose/gateway/3.8/compose.yml"); + void foldersAreComparedAsVersions() { + assertThat(candidates("compose/edge/4.10/kafka.yml", "4.10", "4.10.0EDGE")).startsWith( + "compose/edge/4.10/kafka.yml", + "compose/edge/4.4.0.1/kafka.yml"); } @Test - void versionOutsideTheLineUsesThePathAsIs() { - assertThat(AppTemplateMaterializer.composePathCandidates(PATH, vars("4.4", "4.5.0EDGE"))) - .containsExactly(PATH); + void pathWithoutVersionFoldersIsUsedAsIs() { + assertThat(candidates("compose/generic/default/default.yml", null, "default")) + .containsExactly("compose/generic/default/default.yml"); + assertThat(candidates("compose/edge/3.8/kafka.yml", "3.8", "3.8.0EDGEPE")) + .containsExactly("compose/edge/3.8/kafka.yml"); } - private static Map vars(String composeLine, String version) { - return Map.of("composeLine", composeLine, "version", version); + private static List candidates(String path, String composeLine, String version) { + Map vars = new HashMap<>(); + vars.put("composeLine", composeLine); + vars.put("version", version); + return AppTemplateMaterializer.composePathCandidates(path, vars, EDGE_FOLDERS); } } diff --git a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java index 10e85b6db1..b51d275ab7 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java +++ b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java @@ -17,7 +17,7 @@ public enum EdgeEditionStyle { private final String packageSuffix; public static EdgeEditionStyle getEdgeEditionStyle(String edgeVersion) { - return TbVersionUtils.compare(edgeVersion, "4.4.1") >= 0 ? CE : PE; + return TbVersionUtils.compare(edgeVersion, "4.4.0.1") >= 0 ? CE : PE; } public String replacePlaceholders(String instructions) { From 6b58730a4513250facd426791bc078ad7e32ea5f Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Wed, 7 Oct 2026 12:54:06 +0200 Subject: [PATCH 07/10] Resolve CE-style 4.4+ edge images to their PE-style agent app templates on discovery --- .../agent/compose/ComposeAgentAppCreator.java | 9 ++++++ .../template/AgentAppTemplateSyncService.java | 2 +- .../compose/ComposeAgentAppCreatorTest.java | 32 +++++++++++++++++++ .../server/dao/edge/EdgeEditionStyle.java | 8 +++++ 4 files changed, 50 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreator.java b/application/src/main/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreator.java index e74a0cdb51..21b0376d6c 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreator.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreator.java @@ -9,6 +9,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.RegexUtils; +import org.thingsboard.common.util.TbVersionUtils; import org.thingsboard.server.common.data.agent.Agent; import org.thingsboard.server.common.data.agent.AgentAppEventActionType; import org.thingsboard.server.common.data.agent.AgentAppProfileRelationInfo; @@ -24,6 +25,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.agent.AgentAppProfileService; import org.thingsboard.server.dao.agent.AgentAppRelationService; import org.thingsboard.server.dao.agent.AgentService; +import org.thingsboard.server.dao.edge.EdgeEditionStyle; import org.thingsboard.server.gen.agent.v1.ComposeState; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.agent.AgentAppProvisioner; @@ -103,6 +105,13 @@ public class ComposeAgentAppCreator { private AgentAppTemplate resolveTemplate(ComposeInfo composeInfo) { AgentAppTemplate byAppType = templateService.findByAppTypeAndConfigTypeAndCurrentVersion( composeInfo.appType(), AgentAppConfigType.DOCKER_COMPOSE, composeInfo.version()); + if (byAppType == null && composeInfo.appType() == AgentApplicationType.EDGE && composeInfo.version() != null + && TbVersionUtils.compare(TbVersionUtils.extractStartingDigits(composeInfo.version()), "4.4") >= 0) { + // from 4.4 the same edge release may be published under both edition styles (e.g. 4.4.0EDGEPE and the CE-style 4.4.0EDGE), + // while its template is registered under one of them only; below 4.4 a CE-style tag is Community Edge and stays GENERIC + byAppType = templateService.findByAppTypeAndConfigTypeAndCurrentVersion(AgentApplicationType.EDGE, + AgentAppConfigType.DOCKER_COMPOSE, EdgeEditionStyle.withVersionSuffix(TbVersionUtils.extractStartingDigits(composeInfo.version()))); + } if (byAppType != null) { return byAppType; } diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java index 56cb5d5e62..b265e28e7c 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java @@ -231,7 +231,7 @@ public class AgentAppTemplateSyncService { } private static String withEdgeVersionSuffix(String version) { - return version == null ? null : version + EdgeEditionStyle.getEdgeEditionStyle(version).getVersionSuffix(); + return version == null ? null : EdgeEditionStyle.withVersionSuffix(version); } List filterCurrentlySupportedVersions(List descriptors) { diff --git a/application/src/test/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreatorTest.java b/application/src/test/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreatorTest.java index 42f0700a8c..dfb21bce27 100644 --- a/application/src/test/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreatorTest.java +++ b/application/src/test/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreatorTest.java @@ -181,6 +181,38 @@ class ComposeAgentAppCreatorTest { assertThat(created.getTemplateVersion()).isEqualTo(AgentApplicationType.GENERIC.getDefaultVersion()); } + @Test + void ceStyleEdgeTag_resolvesTemplateRegisteredUnderPeStyleTag() { + AgentAppTemplate peStyleTemplate = template(AgentApplicationType.EDGE, "4.4.0EDGEPE"); + when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion( + AgentApplicationType.EDGE, AgentAppConfigType.DOCKER_COMPOSE, "4.4.0EDGE")).thenReturn(null); + when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion( + AgentApplicationType.EDGE, AgentAppConfigType.DOCKER_COMPOSE, "4.4.0EDGEPE")).thenReturn(peStyleTemplate); + when(appProfileService.findProfileRelationInfosByAgentProfileIdAndAppTypeAndTemplateVersion( + TENANT_ID, AGENT_PROFILE_ID, AgentApplicationType.EDGE, "4.4.0EDGEPE")).thenReturn(List.of()); + + AgentApplication created = creator.createApp(TENANT_ID, AGENT_ID, PROJECT_NAME, + compose("{\"services\":{\"tb-edge\":{\"image\":\"thingsboard/tb-edge:4.4.0EDGE\"}}}")); + + assertThat(created.getAppType()).isEqualTo(AgentApplicationType.EDGE); + assertThat(created.getTemplateVersion()).isEqualTo("4.4.0EDGEPE"); + + // below 4.4 a CE-style tag is Community Edge: no fallback to the PE-style template, the app stays GENERIC + AgentAppTemplate generic = template(AgentApplicationType.GENERIC, AgentApplicationType.GENERIC.getDefaultVersion()); + when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion( + AgentApplicationType.EDGE, AgentAppConfigType.DOCKER_COMPOSE, "4.2.0EDGE")).thenReturn(null); + when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion( + AgentApplicationType.EDGE, AgentAppConfigType.DOCKER_COMPOSE, "4.2.0EDGEPE")).thenReturn(template(AgentApplicationType.EDGE, "4.2.0EDGEPE")); + when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion( + AgentApplicationType.GENERIC, AgentAppConfigType.DOCKER_COMPOSE, AgentApplicationType.GENERIC.getDefaultVersion())).thenReturn(generic); + + AgentApplication community = creator.createApp(TENANT_ID, AGENT_ID, PROJECT_NAME, + compose("{\"services\":{\"tb-edge\":{\"image\":\"thingsboard/tb-edge:4.2.0EDGE\"}}}")); + + assertThat(community.getAppType()).isEqualTo(AgentApplicationType.GENERIC); + assertThat(community.getTemplateVersion()).isEqualTo(AgentApplicationType.GENERIC.getDefaultVersion()); + } + @Test void noTemplateAtAll_returnsNull() { when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion(any(), any(), any())).thenReturn(null); diff --git a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java index b51d275ab7..6cfcb5df2d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java +++ b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java @@ -20,6 +20,14 @@ public enum EdgeEditionStyle { return TbVersionUtils.compare(edgeVersion, "4.4.0.1") >= 0 ? CE : PE; } + /** + * The edge version with the tag suffix its release is published under, e.g. {@code 4.4.0EDGEPE}, {@code 4.4.0.1EDGE}. + * Agent app templates are registered under these versions. + */ + public static String withVersionSuffix(String edgeVersion) { + return edgeVersion + getEdgeEditionStyle(edgeVersion).getVersionSuffix(); + } + public String replacePlaceholders(String instructions) { return instructions .replace("${TB_EDGE_REPO}", dockerRepo) From dd7d773bda60c014943d2c8f58cdc1f61c3f7548 Mon Sep 17 00:00:00 2001 From: Oleksandra Matviienko Date: Tue, 13 Oct 2026 16:03:04 +0200 Subject: [PATCH 08/10] Allowed customer users to list and resolve tenant JS modules GET /api/resource now accepts CUSTOMER_USER and returns only JS_MODULE resources for them; any other requested type, or a request without resourceType, is rejected with 403. GET /api/resource/{type}/{scope}/{key}/info now accepts CUSTOMER_USER; the existing per-resource check already handles customer access. Customer TB_RESOURCE permission checker grants generic READ to any non-public customer user, mirroring its per-resource READ rule. --- .../controller/TbResourceController.java | 12 ++-- .../permission/CustomerUserPermissions.java | 5 ++ .../controller/TbResourceControllerTest.java | 66 +++++++++++++++++++ 3 files changed, 79 insertions(+), 4 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java b/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java index ba1988c49e..68f62d24ae 100644 --- a/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java +++ b/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java @@ -175,8 +175,8 @@ public class TbResourceController extends BaseController { @ApiOperation(value = "Get resource info (getResourceInfo)", notes = "Get info for the resource with the given type, scope and key. " + - RESOURCE_INFO_DESCRIPTION + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) - @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") + RESOURCE_INFO_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER) + @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @GetMapping(value = "/resource/{resourceType}/{scope}/{key}/info") public TbResourceInfo getResourceInfo(@Parameter(description = "Type of the resource", schema = @Schema(allowableValues = {"lwm2m_model", "jks", "pkcs_12", "js_module", "dashboard"})) @PathVariable("resourceType") String resourceTypeStr, @@ -286,8 +286,9 @@ public class TbResourceController extends BaseController { @ApiOperation(value = "Get Resource Infos (getResources)", notes = "Returns a page of Resource Info objects owned by tenant or sysadmin. " + - PAGE_DATA_PARAMETERS + RESOURCE_INFO_DESCRIPTION + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) - @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") + "Customer users may request only 'JS_MODULE' resources, so the 'resourceType' parameter is mandatory for them. " + + PAGE_DATA_PARAMETERS + RESOURCE_INFO_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER) + @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @GetMapping(value = "/resource") public PageData getResources(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @@ -322,6 +323,9 @@ public class TbResourceController extends BaseController { filterResourceTypes.remove(ResourceType.IMAGE); filterResourceTypes.remove(ResourceType.DASHBOARD); } + if (getCurrentUser().isCustomerUser() && !filterResourceTypes.equals(Set.of(ResourceType.JS_MODULE))) { + throw permissionDenied(); + } filter.resourceTypes(filterResourceTypes); if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) { return checkNotNull(resourceService.findTenantResourcesByTenantId(filter.build(), pageLink)); diff --git a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java index 98a2fc05fc..2eab59f385 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java +++ b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java @@ -294,6 +294,11 @@ public class CustomerUserPermissions extends AbstractPermissions { private static final PermissionChecker customerResourcePermissionChecker = new PermissionChecker() { + @Override + public boolean hasPermission(SecurityUser user, Resource resource, Operation operation) { + return operation == Operation.READ && user.getUserPrincipal().getType() != UserPrincipal.Type.PUBLIC_ID; + } + @Override public boolean hasPermission(SecurityUser user, Operation operation, TbResourceId resourceId, TbResourceInfo resource) { if (resource.getResourceType() == null || !resource.getResourceType().isCustomerAccess()) { diff --git a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java index edd1fbefb1..afa5e143b3 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java @@ -965,6 +965,72 @@ public class TbResourceControllerTest extends AbstractControllerTest { "You don't have permission to perform this operation!"); } + @Test + public void testFindJsModules_customerUser() throws Exception { + loginSysAdmin(); + TbResourceInfo systemJsModule = saveResource("System js module", ResourceType.JS_MODULE, "system_" + JS_TEST_FILE_NAME); + + loginTenantAdmin(); + TbResourceInfo tenantJsModule = saveResource("Tenant js module", ResourceType.JS_MODULE, JS_TEST_FILE_NAME); + saveResource("Jks resource", ResourceType.JKS, DEFAULT_FILE_NAME); + + loginNewCustomerUserWithoutPermissions(); + PageData pageData = doGetTypedWithPageLink("/api/resource?resourceType=JS_MODULE&", + new TypeReference<>() { + }, new PageLink(100)); + Assert.assertTrue(pageData.getData().contains(tenantJsModule)); + Assert.assertTrue(pageData.getData().contains(systemJsModule)); + + String msg = "You don't have permission to perform this operation!"; + doGet("/api/resource?resourceType=JKS&pageSize=10&page=0") + .andExpect(status().isForbidden()) + .andExpect(statusReason(containsString(msg))); + doGet("/api/resource?resourceType=JS_MODULE,JKS&pageSize=10&page=0") + .andExpect(status().isForbidden()) + .andExpect(statusReason(containsString(msg))); + doGet("/api/resource?resourceType=IMAGE&pageSize=10&page=0") + .andExpect(status().isForbidden()) + .andExpect(statusReason(containsString(msg))); + doGet("/api/resource?pageSize=10&page=0") + .andExpect(status().isForbidden()) + .andExpect(statusReason(containsString(msg))); + + loginDifferentTenant(); + loginDifferentTenantCustomer(); + pageData = doGetTypedWithPageLink("/api/resource?resourceType=JS_MODULE&", + new TypeReference<>() { + }, new PageLink(100)); + Assert.assertFalse(pageData.getData().contains(tenantJsModule)); + Assert.assertTrue(pageData.getData().contains(systemJsModule)); + + loginTenantAdmin(); + EntityGroupInfo deviceGroup = createSharedPublicEntityGroup("Public device group", EntityType.DEVICE, customerId); + String publicId = deviceGroup.getAdditionalInfo().get("publicCustomerId").asText(); + resetTokens(); + JsonNode tokens = doPost("/api/auth/login/public", JacksonUtil.toJsonNode("{\"publicId\": \"" + publicId + "\"}"), JsonNode.class); + this.token = tokens.get("token").asText(); + doGet("/api/resource?resourceType=JS_MODULE&pageSize=10&page=0") + .andExpect(status().isForbidden()) + .andExpect(statusReason(containsString("You don't have permission to perform 'READ' operation with 'TB_RESOURCE' resource!"))); + + loginSysAdmin(); + doDelete("/api/resource/" + systemJsModule.getId().getId().toString()) + .andExpect(status().isOk()); + } + + @Test + public void testGetResourceInfo_customerUser() throws Exception { + loginTenantAdmin(); + TbResourceInfo jsModule = saveResource("Tenant js module", ResourceType.JS_MODULE, JS_TEST_FILE_NAME); + TbResourceInfo jks = saveResource("Jks resource", ResourceType.JKS, DEFAULT_FILE_NAME); + + loginCustomerUser(); + TbResourceInfo foundJsModule = doGet("/api/resource/js_module/tenant/" + jsModule.getResourceKey() + "/info", TbResourceInfo.class); + Assert.assertEquals(jsModule, foundJsModule); + doGet("/api/resource/jks/tenant/" + jks.getResourceKey() + "/info") + .andExpect(status().isForbidden()); + } + @Test public void testFindAllResource_tenantUserWithoutPermission() throws Exception { String apiResources = loginTenantAdminAndCreateResources(); From b74cdd59b7bcc6b092cce2df3cb803257e547408 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 15 Oct 2026 11:36:14 +0200 Subject: [PATCH 09/10] Move CE-style edge cutoff back to 4.4.1 --- .../agent/template/AppTemplateMaterializer.java | 4 ++-- .../service/agent/template/VersionFolders.java | 2 +- .../AgentAppTemplateSyncServiceTest.java | 16 ++++++++-------- .../template/AppTemplateMaterializerTest.java | 14 +++++++------- .../server/dao/edge/EdgeEditionStyle.java | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java index 294b41f6b2..ac2cc725e6 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java @@ -169,8 +169,8 @@ public class AppTemplateMaterializer { /** * Load the compose body for {@code path}, taking the file from the newest version folder that has it. For version - * {@code 4.4.1} and {@code compose/edge/4.4/kafka.yml} with folders {@code 4.3, 4.4, 4.4.0.1} under - * {@code compose/edge}, this tries {@code compose/edge/4.4.0.1/kafka.yml}, then {@code compose/edge/4.4/kafka.yml}, + * {@code 4.4.2} and {@code compose/edge/4.4/kafka.yml} with folders {@code 4.3, 4.4, 4.4.1} under + * {@code compose/edge}, this tries {@code compose/edge/4.4.1/kafka.yml}, then {@code compose/edge/4.4/kafka.yml}, * then {@code compose/edge/4.3/kafka.yml}. Falls through to an error (so the version is skipped) only when no * candidate exists. */ diff --git a/application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java b/application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java index 7abcc2eb36..0dcc4e11f9 100644 --- a/application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java +++ b/application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java @@ -9,7 +9,7 @@ import java.util.List; import java.util.regex.Pattern; /** - * Version-named folders of the templates repo (e.g. {@code templates/since/4.4.0.1}, {@code compose/edge/4.4}): a + * Version-named folders of the templates repo (e.g. {@code templates/since/4.4.1}, {@code compose/edge/4.4}): a * folder applies to its own version and every later one, until a newer folder exists. */ final class VersionFolders { diff --git a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java index 0c389ec57d..c77fa79cf2 100644 --- a/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java @@ -151,7 +151,7 @@ class AgentAppTemplateSyncServiceTest { } @Test - void appendEdgeVersionSuffixSwitchesToCeStyleFrom4401() { + void appendEdgeVersionSuffixSwitchesToCeStyleFrom441() { List result = AgentAppTemplateSyncService.appendEdgeVersionSuffix(List.of( new AppVersionDescriptor("4.3.1.6", "4.4.0", true), new AppVersionDescriptor("4.4.0", "4.4.0.1", false), @@ -159,9 +159,9 @@ class AgentAppTemplateSyncServiceTest { new AppVersionDescriptor("4.4.1", null, false))); assertThat(result).extracting(AppVersionDescriptor::getVersion) - .containsExactly("4.3.1.6EDGEPE", "4.4.0EDGEPE", "4.4.0.1EDGE", "4.4.1EDGE"); + .containsExactly("4.3.1.6EDGEPE", "4.4.0EDGEPE", "4.4.0.1EDGEPE", "4.4.1EDGE"); assertThat(result).extracting(AppVersionDescriptor::getNextVersion) - .containsExactly("4.4.0EDGEPE", "4.4.0.1EDGE", "4.4.1EDGE", null); + .containsExactly("4.4.0EDGEPE", "4.4.0.1EDGEPE", "4.4.1EDGE", null); } @Test @@ -175,19 +175,19 @@ class AgentAppTemplateSyncServiceTest { @Test void sinceFolderReplacesOnlyTheTemplatesItContains() { - AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.0.1PE-SNAPSHOT"); + AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.1PE-SNAPSHOT"); assertThat(service.getTemplateFiles()).extracting(RepoFile::path).containsExactlyInAnyOrder( - "templates/since/4.4.0.1/template-EDGE-DOCKER_COMPOSE.json", + "templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json", "templates/template-GATEWAY-DOCKER_COMPOSE.json"); } @Test void versionWithoutItsOwnSinceFolderUsesTheNewestLowerOne() { - AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.1"); + AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.2"); assertThat(service.getTemplateFiles()).extracting(RepoFile::path).containsExactlyInAnyOrder( - "templates/since/4.4.0.1/template-EDGE-DOCKER_COMPOSE.json", + "templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json", "templates/template-GATEWAY-DOCKER_COMPOSE.json"); } @@ -209,7 +209,7 @@ class AgentAppTemplateSyncServiceTest { file("templates/README.md"))); when(gitSyncService.listFiles("agent-app-templates", "templates/since", 3, FileType.FILE)).thenReturn(List.of( file("templates/since/4.9/template-EDGE-DOCKER_COMPOSE.json"), - file("templates/since/4.4.0.1/template-EDGE-DOCKER_COMPOSE.json"), + file("templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json"), file("templates/since/4.5/template-GATEWAY-DOCKER_COMPOSE.json"), file("templates/since/4.11/template-GATEWAY-DOCKER_COMPOSE.json"), file("templates/since/draft/template-EDGE-DOCKER_COMPOSE.json"))); diff --git a/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java b/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java index 5e432af38d..27e36c664e 100644 --- a/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java +++ b/application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java @@ -14,7 +14,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AppTemplateMaterializerTest { private static final Function> EDGE_FOLDERS = parent -> parent.equals("compose/edge") - ? List.of("3.9", "4.3", "4.4", "4.4.0.1", "4.10", "latest") + ? List.of("3.9", "4.3", "4.4", "4.4.1", "4.10", "latest") : List.of(); @Test @@ -27,25 +27,25 @@ class AppTemplateMaterializerTest { @Test void versionWithItsOwnFolderUsesItFirst() { - assertThat(candidates("compose/edge/4.4/kafka.yml", "4.4", "4.4.0.1EDGE")).startsWith( - "compose/edge/4.4.0.1/kafka.yml", + assertThat(candidates("compose/edge/4.4/kafka.yml", "4.4", "4.4.1EDGE")).startsWith( + "compose/edge/4.4.1/kafka.yml", "compose/edge/4.4/kafka.yml"); } @Test void versionWithoutItsOwnFolderFallsBackToTheNewestLowerOne() { - assertThat(candidates("compose/edge/4.4/kafka.yml", "4.4", "4.4.1EDGE")).startsWith( - "compose/edge/4.4.0.1/kafka.yml", + assertThat(candidates("compose/edge/4.4/kafka.yml", "4.4", "4.4.2EDGE")).startsWith( + "compose/edge/4.4.1/kafka.yml", "compose/edge/4.4/kafka.yml"); assertThat(candidates("compose/edge/4.5/kafka.yml", "4.5", "4.5.0EDGE")).startsWith( - "compose/edge/4.4.0.1/kafka.yml"); + "compose/edge/4.4.1/kafka.yml"); } @Test void foldersAreComparedAsVersions() { assertThat(candidates("compose/edge/4.10/kafka.yml", "4.10", "4.10.0EDGE")).startsWith( "compose/edge/4.10/kafka.yml", - "compose/edge/4.4.0.1/kafka.yml"); + "compose/edge/4.4.1/kafka.yml"); } @Test diff --git a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java index 6cfcb5df2d..1c5b08d5cb 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java +++ b/dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java @@ -17,11 +17,11 @@ public enum EdgeEditionStyle { private final String packageSuffix; public static EdgeEditionStyle getEdgeEditionStyle(String edgeVersion) { - return TbVersionUtils.compare(edgeVersion, "4.4.0.1") >= 0 ? CE : PE; + return TbVersionUtils.compare(edgeVersion, "4.4.1") >= 0 ? CE : PE; } /** - * The edge version with the tag suffix its release is published under, e.g. {@code 4.4.0EDGEPE}, {@code 4.4.0.1EDGE}. + * The edge version with the tag suffix its release is published under, e.g. {@code 4.4.0EDGEPE}, {@code 4.4.1EDGE}. * Agent app templates are registered under these versions. */ public static String withVersionSuffix(String edgeVersion) { From ca1b84ca5ab5ff02837eb6e2896f514e9e701100 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Fri, 16 Oct 2026 09:29:00 +0200 Subject: [PATCH 10/10] Add (tenant_id, id) index on calculated_field for tenant-scoped paging Calculated field actors page through each tenant's calculated fields on startup (WHERE tenant_id = ? ORDER BY id LIMIT ?). With no index leading on tenant_id, every page and its count query scan the whole table and sort, so startup cost grows with tenants x table size. Ship the index in schema-entities-idx.sql for new installs and as a new 4.4.1.0 LTS migration for existing ones (4.4.0.0 is already released, and the range lower bound is exclusive). --- .../upgrade/lts/4.4.1.0/schema_update.sql | 9 ++++++ .../install/lts/V4_4_1_0Migration.java | 31 +++++++++++++++++++ .../install/lts/MigrationIntegrationTest.java | 25 +++++++++++++++ .../resources/sql/schema-entities-idx.sql | 2 ++ 4 files changed, 67 insertions(+) create mode 100644 application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql create mode 100644 application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_1_0Migration.java diff --git a/application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql b/application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql new file mode 100644 index 0000000000..758854f92b --- /dev/null +++ b/application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql @@ -0,0 +1,9 @@ +-- +-- SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +-- SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +-- SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +-- + +-- Tenant-scoped paging over calculated fields (WHERE tenant_id = ? ORDER BY id LIMIT ?), issued for every tenant +-- when the calculated field actors initialize, otherwise scans the whole table and sorts on each call. +CREATE INDEX IF NOT EXISTS idx_calculated_field_tenant_id_id ON calculated_field(tenant_id, id); diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_1_0Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_1_0Migration.java new file mode 100644 index 0000000000..1d91bc0e82 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_1_0Migration.java @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +package org.thingsboard.server.service.install.lts; + +import org.springframework.stereotype.Component; +import org.thingsboard.server.queue.util.TbCoreComponent; + +/** + * Registration-only migration with no {@link #apply()} (no data migration). + *

+ * {@link MigrationService} selects migrations from the injected {@link Migration} beans, not from the + * on-disk {@code data/upgrade/lts//} directories. So this bean is what makes the runner discover + * version {@code 4.4.1.0} and execute its {@code data/upgrade/lts/4.4.1.0/schema_update.sql}, which adds the + * {@code idx_calculated_field_tenant_id_id} index used by tenant-scoped calculated field paging. + *

+ * It needs a slot of its own rather than {@code 4.4.0.0}: that version is already released, and + * {@link Version#isInRange} is exclusive at the lower bound, so an installation already on {@code 4.4.0.0} + * would never pick up a change added there. + *

+ * The dir/bean consistency (both ways) is guarded by a test in {@code MigrationIntegrationTest}. + */ +@Component +@TbCoreComponent +public class V4_4_1_0Migration implements Migration { + + @Override + public String getVersion() { + return "4.4.1.0"; + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java index 4d0e570e04..bbdb95c466 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java @@ -451,6 +451,25 @@ public class MigrationIntegrationTest extends AbstractControllerTest { * older script legitimately behind. What may never happen is a script declaring a clause the fresh-install * DDL does not. The single-row index is compared exactly: there is only ever one right form of it. */ + @Test + public void appliesSchemaForV4410CreatesCalculatedFieldTenantIdIndex() { + // The test-context schema already ships the index (schema-entities-idx.sql), so drop it first to prove the + // 4.4.1.0 schema_update.sql re-creates it. The finally block restores it for the shared DaoSqlTest schema. + try { + jdbcTemplate.execute("DROP INDEX IF EXISTS idx_calculated_field_tenant_id_id"); + assertFalse(indexExists("idx_calculated_field_tenant_id_id")); + + migrationService.applyMigrations("4.4.0.0", "4.4.1.0", false, () -> {}); + + assertTrue(indexExists("idx_calculated_field_tenant_id_id")); + assertEquals("CREATE INDEX idx_calculated_field_tenant_id_id ON public.calculated_field USING btree (tenant_id, id)", + jdbcTemplate.queryForObject("SELECT indexdef FROM pg_indexes WHERE indexname = ?", String.class, + "idx_calculated_field_tenant_id_id")); + } finally { + jdbcTemplate.execute("CREATE INDEX IF NOT EXISTS idx_calculated_field_tenant_id_id ON calculated_field(tenant_id, id)"); + } + } + @Test public void everyTbClusterDdlCopyIsConsistentWithSchemaEntities() { String schemaEntities = readResource("sql/schema-entities.sql"); @@ -707,6 +726,12 @@ public class MigrationIntegrationTest extends AbstractControllerTest { return Boolean.TRUE.equals(exists); } + private boolean indexExists(String indexName) { + Boolean exists = jdbcTemplate.queryForObject( + "SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = ?)", Boolean.class, indexName); + return Boolean.TRUE.equals(exists); + } + private boolean constraintExists(String constraintName) { Boolean exists = jdbcTemplate.queryForObject( "SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ?)", Boolean.class, constraintName); diff --git a/dao/src/main/resources/sql/schema-entities-idx.sql b/dao/src/main/resources/sql/schema-entities-idx.sql index 1cf38b7a03..bf1f2c3a27 100644 --- a/dao/src/main/resources/sql/schema-entities-idx.sql +++ b/dao/src/main/resources/sql/schema-entities-idx.sql @@ -181,3 +181,5 @@ CREATE INDEX IF NOT EXISTS idx_iot_hub_installed_item_tenant_id ON iot_hub_insta CREATE INDEX IF NOT EXISTS idx_iot_hub_installed_item_item_type ON iot_hub_installed_item(tenant_id, item_type); CREATE INDEX IF NOT EXISTS idx_iot_hub_installed_item_item_id ON iot_hub_installed_item(tenant_id, item_id); + +CREATE INDEX IF NOT EXISTS idx_calculated_field_tenant_id_id ON calculated_field(tenant_id, id);