Browse Source

Merge branch 'rc'

pull/16335/merge
Viacheslav Klimov 2 months ago
parent
commit
e5fda37448
Failed to extract signature
  1. 4
      application/src/main/data/json/edge/instructions/install/centos/instructions.md
  2. 2
      application/src/main/data/json/edge/instructions/install/docker/instructions.md
  3. 4
      application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md
  4. 6
      application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md
  5. 4
      application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md
  6. 2
      application/src/main/data/json/edge/instructions/upgrade/docker/upgrade_db.md
  7. 6
      application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md
  8. 9
      application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql
  9. 12
      application/src/main/java/org/thingsboard/server/controller/TbResourceController.java
  10. 9
      application/src/main/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreator.java
  11. 62
      application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java
  12. 79
      application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java
  13. 32
      application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java
  14. 13
      application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeInstallInstructionsService.java
  15. 17
      application/src/main/java/org/thingsboard/server/service/edge/instructions/DefaultEdgeUpgradeInstructionsService.java
  16. 31
      application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_1_0Migration.java
  17. 5
      application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
  18. 66
      application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java
  19. 32
      application/src/test/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreatorTest.java
  20. 79
      application/src/test/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncServiceTest.java
  21. 65
      application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java
  22. 25
      application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java
  23. 5
      common/data/src/main/java/org/thingsboard/server/common/data/agent/AgentApplicationType.java
  24. 8
      common/data/src/test/java/org/thingsboard/server/common/data/agent/AgentApplicationTypeTest.java
  25. 36
      dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java
  26. 2
      dao/src/main/resources/sql/schema-entities-idx.sql

4
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: Download installation package:
```bash ```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} {:copy-code}
``` ```
Go to the download repository and install ThingsBoard Edge service: Go to the download repository and install ThingsBoard Edge service:
```bash ```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} {:copy-code}
``` ```

2
application/src/main/data/json/edge/instructions/install/docker/instructions.md

@ -24,7 +24,7 @@ Add the following lines to the yml file:
services: services:
mytbedge: mytbedge:
restart: always restart: always
image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}"
ports: ports:
- "8080:8080" - "8080:8080"
- "1883:1883" - "1883:1883"

4
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: Download the installation package:
```bash ```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} {:copy-code}
``` ```
Go to the download repository and install ThingsBoard Edge service: Go to the download repository and install ThingsBoard Edge service:
```bash ```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} {:copy-code}
``` ```

6
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: ThingsBoard Edge package download:
```bash ```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} {:copy-code}
``` ```
Install package: Install package:
```bash ```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} {:copy-code}
``` ```

4
application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md

@ -8,11 +8,11 @@ nano docker-compose.yml
services: services:
mytbedge: mytbedge:
restart: always 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: Execute the following commands to up this docker compose directly:
```bash ```bash

2
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: services:
mytbedge: mytbedge:
restart: on-failure restart: on-failure
image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}"
environment: environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/tb-edge SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/tb-edge
volumes: volumes:

6
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: ThingsBoard Edge package download:
```bash ```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} {:copy-code}
``` ```
Install package: Install package:
```bash ```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} {:copy-code}
``` ```

9
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);

12
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)", @ApiOperation(value = "Get resource info (getResourceInfo)",
notes = "Get info for the resource with the given type, scope and key. " + notes = "Get info for the resource with the given type, scope and key. " +
RESOURCE_INFO_DESCRIPTION + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) RESOURCE_INFO_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@GetMapping(value = "/resource/{resourceType}/{scope}/{key}/info") @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"})) public TbResourceInfo getResourceInfo(@Parameter(description = "Type of the resource", schema = @Schema(allowableValues = {"lwm2m_model", "jks", "pkcs_12", "js_module", "dashboard"}))
@PathVariable("resourceType") String resourceTypeStr, @PathVariable("resourceType") String resourceTypeStr,
@ -286,8 +286,9 @@ public class TbResourceController extends BaseController {
@ApiOperation(value = "Get Resource Infos (getResources)", @ApiOperation(value = "Get Resource Infos (getResources)",
notes = "Returns a page of Resource Info objects owned by tenant or sysadmin. " + notes = "Returns a page of Resource Info objects owned by tenant or sysadmin. " +
PAGE_DATA_PARAMETERS + RESOURCE_INFO_DESCRIPTION + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) "Customer users may request only 'JS_MODULE' resources, so the 'resourceType' parameter is mandatory for them. " +
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") PAGE_DATA_PARAMETERS + RESOURCE_INFO_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@GetMapping(value = "/resource") @GetMapping(value = "/resource")
public PageData<TbResourceInfo> getResources(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) public PageData<TbResourceInfo> getResources(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true)
@RequestParam int pageSize, @RequestParam int pageSize,
@ -322,6 +323,9 @@ public class TbResourceController extends BaseController {
filterResourceTypes.remove(ResourceType.IMAGE); filterResourceTypes.remove(ResourceType.IMAGE);
filterResourceTypes.remove(ResourceType.DASHBOARD); filterResourceTypes.remove(ResourceType.DASHBOARD);
} }
if (getCurrentUser().isCustomerUser() && !filterResourceTypes.equals(Set.of(ResourceType.JS_MODULE))) {
throw permissionDenied();
}
filter.resourceTypes(filterResourceTypes); filter.resourceTypes(filterResourceTypes);
if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) { if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) {
return checkNotNull(resourceService.findTenantResourcesByTenantId(filter.build(), pageLink)); return checkNotNull(resourceService.findTenantResourcesByTenantId(filter.build(), pageLink));

9
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.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.RegexUtils; 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.Agent;
import org.thingsboard.server.common.data.agent.AgentAppEventActionType; import org.thingsboard.server.common.data.agent.AgentAppEventActionType;
import org.thingsboard.server.common.data.agent.AgentAppProfileRelationInfo; 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.AgentAppProfileService;
import org.thingsboard.server.dao.agent.AgentAppRelationService; import org.thingsboard.server.dao.agent.AgentAppRelationService;
import org.thingsboard.server.dao.agent.AgentService; 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.gen.agent.v1.ComposeState;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.agent.AgentAppProvisioner; import org.thingsboard.server.service.agent.AgentAppProvisioner;
@ -103,6 +105,13 @@ public class ComposeAgentAppCreator {
private AgentAppTemplate resolveTemplate(ComposeInfo composeInfo) { private AgentAppTemplate resolveTemplate(ComposeInfo composeInfo) {
AgentAppTemplate byAppType = templateService.findByAppTypeAndConfigTypeAndCurrentVersion( AgentAppTemplate byAppType = templateService.findByAppTypeAndConfigTypeAndCurrentVersion(
composeInfo.appType(), AgentAppConfigType.DOCKER_COMPOSE, composeInfo.version()); 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) { if (byAppType != null) {
return byAppType; return byAppType;
} }

62
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.AgentApplicationType;
import org.thingsboard.server.common.data.agent.config.AgentAppConfigType; import org.thingsboard.server.common.data.agent.config.AgentAppConfigType;
import org.thingsboard.server.common.data.util.CollectionsUtil; 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.dao.sql.agent.AppTemplateRegistry;
import org.thingsboard.server.queue.util.AfterStartUp; import org.thingsboard.server.queue.util.AfterStartUp;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
@ -39,8 +40,10 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -68,7 +71,8 @@ public class AgentAppTemplateSyncService {
private static final int APP_TYPE_GROUP_NUM = 1; private static final int APP_TYPE_GROUP_NUM = 1;
private static final int CONFIG_TYPE_GROUP_NUM = 2; private static final int CONFIG_TYPE_GROUP_NUM = 2;
private static final String REPO_KEY = "agent-app-templates"; private static final String REPO_KEY = "agent-app-templates";
private static final String EDGE_IMAGE_VERSION_SUFFIX = "EDGEPE"; // <basePath>/since/<version>/ holds templates that replace the same-named base ones from that platform version on
private static final String SINCE_DIR = "since";
private static final Duration UPDATE_SERVER_CONNECT_TIMEOUT = Duration.ofSeconds(10); private static final Duration UPDATE_SERVER_CONNECT_TIMEOUT = Duration.ofSeconds(10);
private static final Duration UPDATE_SERVER_READ_TIMEOUT = Duration.ofSeconds(30); private static final Duration UPDATE_SERVER_READ_TIMEOUT = Duration.ofSeconds(30);
@ -125,7 +129,7 @@ public class AgentAppTemplateSyncService {
continue; continue;
} }
MaterializationResult result = materializer.materialize( MaterializationResult result = materializer.materialize(
rawTemplate, appType, configType, descriptors, composeLoader()); rawTemplate, appType, configType, descriptors, composeLoader(), folderLister());
if (result.getByVersion().isEmpty()) { if (result.getByVersion().isEmpty()) {
log.warn("Materialized no versions for {}-{} (the version graph is empty or unreachable); " + log.warn("Materialized no versions for {}-{} (the version graph is empty or unreachable); " +
"keeping the previously registered templates", appType, configType); "keeping the previously registered templates", appType, configType);
@ -147,12 +151,47 @@ public class AgentAppTemplateSyncService {
return new RestTemplate(factory); return new RestTemplate(factory);
} }
private List<RepoFile> getTemplateFiles() { /**
return gitSyncService.listFiles(REPO_KEY, basePath, 1, FileType.FILE).stream() * Base templates overridden per file name by {@code since/<version>/} 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<RepoFile> getTemplateFiles() {
String platform = TbVersionUtils.extractStartingDigits(projectInfo.getProjectVersion());
Map<String, List<RepoFile>> sinceFilesByVersion = listTemplateFiles(basePath + "/" + SINCE_DIR, 2).stream()
.collect(Collectors.groupingBy(AgentAppTemplateSyncService::sinceVersion));
Map<String, RepoFile> byName = new LinkedHashMap<>();
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());
}
// Template files the given number of folders below path
private List<RepoFile> 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)) .filter(file -> RegexUtils.matches(file.name(), TEMPLATE_FILE_PATTERN))
.collect(Collectors.toList()); .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<String, List<String>> folderLister() {
Map<String, List<String>> 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<String, JsonNode> composeLoader() { private Function<String, JsonNode> composeLoader() {
// Returns null when the file is absent so the materializer can probe more/less specific // 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. // version subfolders (e.g. compose/edge/4.3/4.3.1 before compose/edge/4.3) and pick the closest match.
@ -169,8 +208,8 @@ public class AgentAppTemplateSyncService {
private List<AppVersionDescriptor> resolveDescriptors(AgentApplicationType appType) { private List<AppVersionDescriptor> resolveDescriptors(AgentApplicationType appType) {
return switch (appType) { return switch (appType) {
case EDGE -> appendVersionSuffix(filterCurrentlySupportedVersions( case EDGE -> appendEdgeVersionSuffix(filterCurrentlySupportedVersions(
filterVersionsWithoutTemplates(edgeDescriptors(), minSupportedEdgeVersion, appType)), EDGE_IMAGE_VERSION_SUFFIX); filterVersionsWithoutTemplates(edgeDescriptors(), minSupportedEdgeVersion, appType)));
case GATEWAY -> filterVersionsWithoutTemplates( case GATEWAY -> filterVersionsWithoutTemplates(
buildDescriptors(gatewayVersionGraph(), "gatewayVersions", "nextGatewayVersion", false), buildDescriptors(gatewayVersionGraph(), "gatewayVersions", "nextGatewayVersion", false),
minSupportedGatewayVersion, appType); minSupportedGatewayVersion, appType);
@ -178,18 +217,23 @@ public class AgentAppTemplateSyncService {
}; };
} }
static List<AppVersionDescriptor> appendVersionSuffix(List<AppVersionDescriptor> 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<AppVersionDescriptor> appendEdgeVersionSuffix(List<AppVersionDescriptor> descriptors) {
if (CollectionsUtil.isEmpty(descriptors)) { if (CollectionsUtil.isEmpty(descriptors)) {
return descriptors; return descriptors;
} }
return descriptors.stream() return descriptors.stream()
.map(d -> new AppVersionDescriptor( .map(d -> new AppVersionDescriptor(
d.getVersion() + suffix, withEdgeVersionSuffix(d.getVersion()),
d.getNextVersion() == null ? null : d.getNextVersion() + suffix, withEdgeVersionSuffix(d.getNextVersion()),
d.isRequiresUpdateDb())) d.isRequiresUpdateDb()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
private static String withEdgeVersionSuffix(String version) {
return version == null ? null : EdgeEditionStyle.withVersionSuffix(version);
}
List<AppVersionDescriptor> filterCurrentlySupportedVersions(List<AppVersionDescriptor> descriptors) { List<AppVersionDescriptor> filterCurrentlySupportedVersions(List<AppVersionDescriptor> descriptors) {
if (CollectionsUtil.isEmpty(descriptors)) { if (CollectionsUtil.isEmpty(descriptors)) {
return descriptors; return descriptors;

79
application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java

@ -17,9 +17,8 @@ import org.thingsboard.server.common.data.agent.step.ComposeTypeChoiceStep;
import org.thingsboard.server.common.data.agent.template.AgentAppTemplate; import org.thingsboard.server.common.data.agent.template.AgentAppTemplate;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.agent.StepLinkedListUtils; import org.thingsboard.server.dao.agent.StepLinkedListUtils;
import org.thingsboard.server.dao.edge.EdgeEditionStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -69,7 +68,8 @@ public class AppTemplateMaterializer {
AgentApplicationType appType, AgentApplicationType appType,
AgentAppConfigType configType, AgentAppConfigType configType,
List<AppVersionDescriptor> descriptors, List<AppVersionDescriptor> descriptors,
Function<String, JsonNode> composeLoader) { Function<String, JsonNode> composeLoader,
Function<String, List<String>> folderLister) {
Map<String, AgentAppTemplate> byVersion = new LinkedHashMap<>(); Map<String, AgentAppTemplate> byVersion = new LinkedHashMap<>();
AgentAppTemplate latest = null; AgentAppTemplate latest = null;
@ -81,7 +81,7 @@ public class AppTemplateMaterializer {
try { try {
Map<String, Object> vars = buildVars(d); Map<String, Object> vars = buildVars(d);
AgentAppTemplate template = materializeOne(rawTemplate, appType, configType, AgentAppTemplate template = materializeOne(rawTemplate, appType, configType,
d.getVersion(), d.getNextVersion(), vars, composeLoader); d.getVersion(), d.getNextVersion(), vars, composeLoader, folderLister);
byVersion.put(d.getVersion(), template); byVersion.put(d.getVersion(), template);
if (d.getNextVersion() == null) { if (d.getNextVersion() == null) {
latest = template; latest = template;
@ -115,7 +115,8 @@ public class AppTemplateMaterializer {
String version, String version,
String nextVersion, String nextVersion,
Map<String, Object> vars, Map<String, Object> vars,
Function<String, JsonNode> composeLoader) { Function<String, JsonNode> composeLoader,
Function<String, List<String>> folderLister) {
JsonNode substituted = TemplateVarSubstitutor.substitute(rawTemplate, vars); JsonNode substituted = TemplateVarSubstitutor.substitute(rawTemplate, vars);
AgentAppTemplate template = JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER AgentAppTemplate template = JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER
@ -127,7 +128,7 @@ public class AppTemplateMaterializer {
template.setCurrentVersion(version); template.setCurrentVersion(version);
template.setNextVersion(nextVersion); template.setNextVersion(nextVersion);
resolveComposeTemplates(template.getStartSteps(), vars, composeLoader); resolveComposeTemplates(template.getStartSteps(), vars, composeLoader, folderLister);
Predicate<AgentAppStep> disabled = step -> Predicate<AgentAppStep> disabled = step ->
step.getCondition() != null && !truthy(vars.get(step.getCondition())); step.getCondition() != null && !truthy(vars.get(step.getCondition()));
@ -140,7 +141,8 @@ public class AppTemplateMaterializer {
} }
private void resolveComposeTemplates(List<AgentAppStep> steps, Map<String, Object> vars, private void resolveComposeTemplates(List<AgentAppStep> steps, Map<String, Object> vars,
Function<String, JsonNode> composeLoader) { Function<String, JsonNode> composeLoader,
Function<String, List<String>> folderLister) {
if (steps == null) { if (steps == null) {
return; return;
} }
@ -154,7 +156,7 @@ public class AppTemplateMaterializer {
if (value != null && value.isTextual()) { if (value != null && value.isTextual()) {
String path = value.asText(); String path = value.asText();
if (path.endsWith(".yml") || path.endsWith(".yaml")) { 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)); resolved.put(entry.getKey(), TemplateVarSubstitutor.substitute(compose, vars));
continue; continue;
} }
@ -166,13 +168,15 @@ public class AppTemplateMaterializer {
} }
/** /**
* Load the compose body for {@code path}, preferring the most specific version subfolder that actually exists in * Load the compose body for {@code path}, taking the file from the newest version folder that has it. For version
* the repo. For version {@code 4.3.1.2} with a base {@code composeLine} of {@code 4.3}, this tries * {@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/4.3/4.3.1/4.3.1.2/…}, then {@code …/4.3/4.3.1/…}, then the base {@code …/4.3/…}. Falls through * {@code compose/edge}, this tries {@code compose/edge/4.4.1/kafka.yml}, then {@code compose/edge/4.4/kafka.yml},
* to an error (so the version is skipped, as before) only when no candidate exists. * 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<String, Object> vars, Function<String, JsonNode> composeLoader) { private JsonNode loadMostSpecificCompose(String path, Map<String, Object> vars, Function<String, JsonNode> composeLoader,
List<String> candidates = composePathCandidates(path, vars); Function<String, List<String>> folderLister) {
List<String> candidates = composePathCandidates(path, vars, folderLister);
for (String candidate : candidates) { for (String candidate : candidates) {
JsonNode compose = composeLoader.apply(candidate); JsonNode compose = composeLoader.apply(candidate);
if (compose != null) { if (compose != null) {
@ -183,38 +187,26 @@ public class AppTemplateMaterializer {
} }
/** /**
* Candidate compose paths, most specific first, obtained by expanding the {@code composeLine} folder segment into * Candidate compose paths, newest first: the {@code composeLine} folder of {@code path} is swapped for each sibling
* 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}). * 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.
*/ */
private List<String> composePathCandidates(String path, Map<String, Object> vars) { static List<String> composePathCandidates(String path, Map<String, Object> vars, Function<String, List<String>> folderLister) {
Object lineObj = vars.get("composeLine"); Object line = vars.get("composeLine");
Object versionObj = vars.get("version"); Object version = vars.get("version");
if (lineObj == null || versionObj == null) { String lineFolder = "/" + line + "/";
return List.of(path); if (line == null || version == null || !path.contains(lineFolder)) {
}
String line = lineObj.toString();
String[] parts = TbVersionUtils.extractStartingDigits(versionObj.toString()).split("\\.");
int baseFolderDepth = line.split("\\.").length;
// Dotted prefixes from the composeLine depth up to the full numeric version, e.g. ["4.3","4.3.1","4.3.1.2"].
List<String> dottedPrefixes = new ArrayList<>();
for (int i = baseFolderDepth; i <= parts.length; i++) {
dottedPrefixes.add(String.join(".", Arrays.copyOfRange(parts, 0, i)));
}
// 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); return List.of(path);
} }
String parent = path.substring(0, path.indexOf(lineFolder));
String file = path.substring(path.indexOf(lineFolder) + lineFolder.length());
List<String> folders = VersionFolders.applicableTo(folderLister.apply(parent),
TbVersionUtils.extractStartingDigits(version.toString()));
return folders.isEmpty() ? List.of(path) : folders.stream().map(folder -> parent + "/" + folder + "/" + file).toList();
}
List<String> candidates = new ArrayList<>(); private static String edgeRepo(String version) {
for (int depth = dottedPrefixes.size(); depth >= 1; depth--) { return version == null ? null : EdgeEditionStyle.getEdgeEditionStyle(version).getDockerRepo();
String nestedLine = String.join("/", dottedPrefixes.subList(0, depth));
candidates.add(line.equals(nestedLine)
? path
: path.replaceFirst("/" + Pattern.quote(line) + "/",
"/" + Matcher.quoteReplacement(nestedLine) + "/"));
}
return candidates;
} }
private Map<String, Object> buildVars(AppVersionDescriptor d) { private Map<String, Object> buildVars(AppVersionDescriptor d) {
@ -226,6 +218,9 @@ public class AppTemplateMaterializer {
vars.put("nextVersion", d.getNextVersion()); vars.put("nextVersion", d.getNextVersion());
vars.put("nextEdgeVersion", d.getNextVersion()); vars.put("nextEdgeVersion", d.getNextVersion());
vars.put("nextGatewayVersion", 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("composeLine", composeLine(d.getVersion()));
vars.put("requiresUpdateDb", d.isRequiresUpdateDb()); vars.put("requiresUpdateDb", d.isRequiresUpdateDb());
return vars; return vars;

32
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.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<String> applicableTo(Collection<String> 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();
}
}

13
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.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service; 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.Edge;
import org.thingsboard.server.common.data.edge.EdgeInstructions; 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.dao.util.DeviceConnectivityUtil;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.install.InstallScripts; import org.thingsboard.server.service.install.InstallScripts;
@ -53,8 +55,10 @@ public class DefaultEdgeInstallInstructionsService extends BaseEdgeInstallUpgrad
dockerInstallInstructions = dockerInstallInstructions.replace("${EXTRA_HOSTS}", ""); dockerInstallInstructions = dockerInstallInstructions.replace("${EXTRA_HOSTS}", "");
dockerInstallInstructions = dockerInstallInstructions.replace("${BASE_URL}", baseUrl); dockerInstallInstructions = dockerInstallInstructions.replace("${BASE_URL}", baseUrl);
} }
String edgeVersion = platformEdgeVersion.replace("-SNAPSHOT", "").replace("PE", ""); String edgeVersion = TbVersionUtils.extractStartingDigits(platformEdgeVersion);
dockerInstallInstructions = dockerInstallInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + "EDGEPE"); EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion);
dockerInstallInstructions = edition.replacePlaceholders(dockerInstallInstructions);
dockerInstallInstructions = dockerInstallInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + edition.getVersionSuffix());
dockerInstallInstructions = replacePlaceholders(dockerInstallInstructions, edge); dockerInstallInstructions = replacePlaceholders(dockerInstallInstructions, edge);
return new EdgeInstructions(dockerInstallInstructions); return new EdgeInstructions(dockerInstallInstructions);
} }
@ -63,8 +67,9 @@ public class DefaultEdgeInstallInstructionsService extends BaseEdgeInstallUpgrad
String ubuntuInstallInstructions = readFile(resolveFile(os, "instructions.md")); String ubuntuInstallInstructions = readFile(resolveFile(os, "instructions.md"));
ubuntuInstallInstructions = replacePlaceholders(ubuntuInstallInstructions, edge); ubuntuInstallInstructions = replacePlaceholders(ubuntuInstallInstructions, edge);
ubuntuInstallInstructions = ubuntuInstallInstructions.replace("${BASE_URL}", request.getServerName()); ubuntuInstallInstructions = ubuntuInstallInstructions.replace("${BASE_URL}", request.getServerName());
String edgeVersion = platformEdgeVersion.replace("-SNAPSHOT", "").replace("PE", "pe"); String edgeVersion = TbVersionUtils.extractStartingDigits(platformEdgeVersion);
ubuntuInstallInstructions = ubuntuInstallInstructions.replace("${TB_EDGE_TAG}", getTagVersion(edgeVersion).replace("pe", "")); ubuntuInstallInstructions = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion).replacePlaceholders(ubuntuInstallInstructions);
ubuntuInstallInstructions = ubuntuInstallInstructions.replace("${TB_EDGE_TAG}", getTagVersion(edgeVersion));
return new EdgeInstructions(ubuntuInstallInstructions); return new EdgeInstructions(ubuntuInstallInstructions);
} }

17
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.id.TenantId;
import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.AttributeKvEntry;
import org.thingsboard.server.dao.attributes.AttributesService; 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.queue.util.TbCoreComponent;
import org.thingsboard.server.service.install.InstallScripts; 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"))); StringBuilder result = new StringBuilder(readFile(resolveFile("docker", "upgrade_preparing.md")));
while (edgeUpgradeInfo.getNextEdgeVersion() != null && !platformEdgeVersion.equals(currentEdgeVersion)) { while (edgeUpgradeInfo.getNextEdgeVersion() != null && !platformEdgeVersion.equals(currentEdgeVersion)) {
String edgeVersion = edgeUpgradeInfo.getNextEdgeVersion(); String edgeVersion = edgeUpgradeInfo.getNextEdgeVersion();
EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion);
EdgeEditionStyle fromEdition = EdgeEditionStyle.getEdgeEditionStyle(currentEdgeVersion);
String dockerUpgradeInstructions = readFile(resolveFile("docker", "instructions.md")); String dockerUpgradeInstructions = readFile(resolveFile("docker", "instructions.md"));
if (edgeUpgradeInfo.isRequiresUpdateDb()) { if (edgeUpgradeInfo.isRequiresUpdateDb()) {
String upgradeDb = readFile(resolveFile("docker", "upgrade_db.md")); String upgradeDb = readFile(resolveFile("docker", "upgrade_db.md"));
@ -90,14 +93,16 @@ public class DefaultEdgeUpgradeInstructionsService extends BaseEdgeInstallUpgrad
} else { } else {
dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${UPGRADE_DB}", ""); dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${UPGRADE_DB}", "");
} }
dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + "EDGEPE"); dockerUpgradeInstructions = edition.replacePlaceholders(dockerUpgradeInstructions);
dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${FROM_TB_EDGE_VERSION}", currentEdgeVersion + "EDGEPE"); dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${TB_EDGE_VERSION}", edgeVersion + edition.getVersionSuffix());
dockerUpgradeInstructions = dockerUpgradeInstructions.replace("${FROM_TB_EDGE_VERSION}", currentEdgeVersion + fromEdition.getVersionSuffix());
currentEdgeVersion = edgeVersion; currentEdgeVersion = edgeVersion;
edgeUpgradeInfo = upgradeVersionHashMap.get(edgeUpgradeInfo.getNextEdgeVersion()); edgeUpgradeInfo = upgradeVersionHashMap.get(edgeUpgradeInfo.getNextEdgeVersion());
result.append(dockerUpgradeInstructions); result.append(dockerUpgradeInstructions);
} }
String startService = readFile(resolveFile("docker", "start_service.md")); EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(currentEdgeVersion);
startService = startService.replace("${TB_EDGE_VERSION}", currentEdgeVersion + "EDGEPE"); String startService = edition.replacePlaceholders(readFile(resolveFile("docker", "start_service.md")));
startService = startService.replace("${TB_EDGE_VERSION}", currentEdgeVersion + edition.getVersionSuffix());
result.append(startService); result.append(startService);
return new EdgeInstructions(result.toString()); return new EdgeInstructions(result.toString());
} }
@ -112,6 +117,7 @@ public class DefaultEdgeUpgradeInstructionsService extends BaseEdgeInstallUpgrad
StringBuilder result = new StringBuilder(upgrade_preparing); StringBuilder result = new StringBuilder(upgrade_preparing);
while (edgeUpgradeInfo.getNextEdgeVersion() != null && !platformEdgeVersion.equals(currentEdgeVersion)) { while (edgeUpgradeInfo.getNextEdgeVersion() != null && !platformEdgeVersion.equals(currentEdgeVersion)) {
String edgeVersion = edgeUpgradeInfo.getNextEdgeVersion(); String edgeVersion = edgeUpgradeInfo.getNextEdgeVersion();
EdgeEditionStyle edition = EdgeEditionStyle.getEdgeEditionStyle(edgeVersion);
String linuxUpgradeInstructions = readFile(resolveFile(os, "instructions.md")); String linuxUpgradeInstructions = readFile(resolveFile(os, "instructions.md"));
if (edgeUpgradeInfo.isRequiresUpdateDb()) { if (edgeUpgradeInfo.isRequiresUpdateDb()) {
String upgradeDb = readFile(resolveFile("upgrade_db.md")); String upgradeDb = readFile(resolveFile("upgrade_db.md"));
@ -119,9 +125,10 @@ public class DefaultEdgeUpgradeInstructionsService extends BaseEdgeInstallUpgrad
} else { } else {
linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${UPGRADE_DB}", ""); linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${UPGRADE_DB}", "");
} }
linuxUpgradeInstructions = edition.replacePlaceholders(linuxUpgradeInstructions);
linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${TB_EDGE_TAG}", getTagVersion(edgeVersion)); linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${TB_EDGE_TAG}", getTagVersion(edgeVersion));
linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${FROM_TB_EDGE_TAG}", getTagVersion(currentEdgeVersion)); 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); linuxUpgradeInstructions = linuxUpgradeInstructions.replace("${FROM_TB_EDGE_VERSION}", currentEdgeVersion);
currentEdgeVersion = edgeVersion; currentEdgeVersion = edgeVersion;
edgeUpgradeInfo = upgradeVersionHashMap.get(edgeUpgradeInfo.getNextEdgeVersion()); edgeUpgradeInfo = upgradeVersionHashMap.get(edgeUpgradeInfo.getNextEdgeVersion());

31
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).
* <p>
* {@link MigrationService} selects migrations from the injected {@link Migration} beans, not from the
* on-disk {@code data/upgrade/lts/<version>/} 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.
* <p>
* 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.
* <p>
* 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";
}
}

5
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<TbResourceId, TbResourceInfo>() { private static final PermissionChecker customerResourcePermissionChecker = new PermissionChecker<TbResourceId, TbResourceInfo>() {
@Override
public boolean hasPermission(SecurityUser user, Resource resource, Operation operation) {
return operation == Operation.READ && user.getUserPrincipal().getType() != UserPrincipal.Type.PUBLIC_ID;
}
@Override @Override
public boolean hasPermission(SecurityUser user, Operation operation, TbResourceId resourceId, TbResourceInfo resource) { public boolean hasPermission(SecurityUser user, Operation operation, TbResourceId resourceId, TbResourceInfo resource) {
if (resource.getResourceType() == null || !resource.getResourceType().isCustomerAccess()) { if (resource.getResourceType() == null || !resource.getResourceType().isCustomerAccess()) {

66
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!"); "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<TbResourceInfo> 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 @Test
public void testFindAllResource_tenantUserWithoutPermission() throws Exception { public void testFindAllResource_tenantUserWithoutPermission() throws Exception {
String apiResources = loginTenantAdminAndCreateResources(); String apiResources = loginTenantAdminAndCreateResources();

32
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()); 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 @Test
void noTemplateAtAll_returnsNull() { void noTemplateAtAll_returnsNull() {
when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion(any(), any(), any())).thenReturn(null); when(templateService.findByAppTypeAndConfigTypeAndCurrentVersion(any(), any(), any())).thenReturn(null);

79
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.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness; import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.common.data.agent.AgentApplicationType; import org.thingsboard.server.common.data.agent.AgentApplicationType;
import org.thingsboard.server.dao.sql.agent.AppTemplateRegistry; import org.thingsboard.server.dao.sql.agent.AppTemplateRegistry;
import org.thingsboard.server.service.agent.template.AppTemplateMaterializer.AppVersionDescriptor; import org.thingsboard.server.service.agent.template.AppTemplateMaterializer.AppVersionDescriptor;
import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.sync.GitSyncService; 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.Arrays;
import java.util.List; import java.util.List;
@ -135,10 +138,10 @@ class AgentAppTemplateSyncServiceTest {
} }
@Test @Test
void appendVersionSuffixRewritesBothVersionAndNextVersion() { void appendEdgeVersionSuffixRewritesBothVersionAndNextVersion() {
List<AppVersionDescriptor> result = AgentAppTemplateSyncService.appendVersionSuffix(List.of( List<AppVersionDescriptor> result = AgentAppTemplateSyncService.appendEdgeVersionSuffix(List.of(
new AppVersionDescriptor("4.1.0", "4.2.0", true), 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) assertThat(result).extracting(AppVersionDescriptor::getVersion)
.containsExactly("4.1.0EDGEPE", "4.2.0EDGEPE"); .containsExactly("4.1.0EDGEPE", "4.2.0EDGEPE");
@ -146,4 +149,74 @@ class AgentAppTemplateSyncServiceTest {
assertThat(result.get(0).isRequiresUpdateDb()).isTrue(); assertThat(result.get(0).isRequiresUpdateDb()).isTrue();
assertThat(result.get(1).getNextVersion()).isNull(); assertThat(result.get(1).getNextVersion()).isNull();
} }
@Test
void appendEdgeVersionSuffixSwitchesToCeStyleFrom441() {
List<AppVersionDescriptor> 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", false),
new AppVersionDescriptor("4.4.1", null, false)));
assertThat(result).extracting(AppVersionDescriptor::getVersion)
.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.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 versionWithoutItsOwnSinceFolderUsesTheNewestLowerOne() {
AgentAppTemplateSyncService service = serviceWithTemplateFiles("4.4.2");
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);
}
} }

65
application/src/test/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializerTest.java

@ -0,0 +1,65 @@
// 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.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 Function<String, List<String>> EDGE_FOLDERS = parent -> parent.equals("compose/edge")
? List.of("3.9", "4.3", "4.4", "4.4.1", "4.10", "latest")
: List.of();
@Test
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.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.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.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.1/kafka.yml");
}
@Test
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 List<String> candidates(String path, String composeLine, String version) {
Map<String, Object> vars = new HashMap<>();
vars.put("composeLine", composeLine);
vars.put("version", version);
return AppTemplateMaterializer.composePathCandidates(path, vars, EDGE_FOLDERS);
}
}

25
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 * 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. * 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 @Test
public void everyTbClusterDdlCopyIsConsistentWithSchemaEntities() { public void everyTbClusterDdlCopyIsConsistentWithSchemaEntities() {
String schemaEntities = readResource("sql/schema-entities.sql"); String schemaEntities = readResource("sql/schema-entities.sql");
@ -707,6 +726,12 @@ public class MigrationIntegrationTest extends AbstractControllerTest {
return Boolean.TRUE.equals(exists); 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) { private boolean constraintExists(String constraintName) {
Boolean exists = jdbcTemplate.queryForObject( Boolean exists = jdbcTemplate.queryForObject(
"SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ?)", Boolean.class, constraintName); "SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ?)", Boolean.class, constraintName);

5
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 has no version graph; its single template is materialized and registered under this defaultVersion.
GENERIC(null, "default", null, Collections.emptyList()), GENERIC(null, "default", null, Collections.emptyList()),
// the leading "(?:[^/\s]+/)*" accepts optional registry/namespace segments, so an image pulled through a // 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 // private mirror still matches: patterns are applied with Matcher.matches() over the whole image reference;
EDGE("(?:[^/\\s]+/)*thingsboard/tb-edge-pe:.+", null, EntityType.EDGE, // 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")), List.of("CLOUD_ROUTING_KEY", "CLOUD_ROUTING_SECRET")),
GATEWAY("(?:[^/\\s]+/)*thingsboard/tb-gateway:.+", null, EntityType.DEVICE, GATEWAY("(?:[^/\\s]+/)*thingsboard/tb-gateway:.+", null, EntityType.DEVICE,
gatewayCredentialEnvKeys()); gatewayCredentialEnvKeys());

8
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", "thingsboard/tb-edge-pe:4.2.0",
"registry.example.com/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", "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) { void edgePatternAcceptsDockerHubAndMirroredImages(String image) {
assertThat(AgentApplicationType.EDGE.getMainImagePattern().matcher(image).matches()).isTrue(); assertThat(AgentApplicationType.EDGE.getMainImagePattern().matcher(image).matches()).isTrue();
@ -33,8 +35,10 @@ class AgentApplicationTypeTest {
@ParameterizedTest @ParameterizedTest
@ValueSource(strings = { @ValueSource(strings = {
"thingsboard/tb-edge-pe", "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-pe:4.2.0",
"someone/tb-edge:4.5.0EDGE",
"registry.example.com/thingsboard/tb-gateway:3.8.0" "registry.example.com/thingsboard/tb-gateway:3.8.0"
}) })
void edgePatternStillRejectsAnythingButTheEdgeImage(String image) { void edgePatternStillRejectsAnythingButTheEdgeImage(String image) {

36
dao/src/main/java/org/thingsboard/server/dao/edge/EdgeEditionStyle.java

@ -0,0 +1,36 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
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.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.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)
.replace("${TB_EDGE_PKG_SUFFIX}", packageSuffix);
}
}

2
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_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_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);

Loading…
Cancel
Save