diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a0d336e353..52bba5966c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -152,8 +152,21 @@ rm ~/.testcontainers.properties Open a pull request against `master`. Fill out the pull request template, and make sure: - New or changed behavior has test coverage. -- `mvn license:format` has been run, so new files carry the correct license header. +- `mvn license:format` has been run, so new files carry the correct license header. Do not add + your own copyright or author lines to file headers. - The change builds cleanly: `mvn -pl -am -DskipTests -Dpkg.skip=true test-compile` at minimum for the modules you touched. +- You have signed the Contributor License Agreement (see below). -By contributing, you agree that your contribution is licensed under this project's license (see -[LICENSE](./LICENSE)). +## Contributor License Agreement + +Before we can merge your pull request, you need to sign the ThingsBoard +[Contributor License Agreement](https://cla-assistant.io/thingsboard/thingsboard) (CLA). On your +first pull request a bot posts a link: sign in with GitHub and accept the agreement. You sign once, +and it covers all your contributions to this repository, including those made before you signed. + +You keep the copyright in your contributions. The CLA grants ThingsBoard, Inc. a license to use and +distribute them, including under this project's license (see [LICENSE](./LICENSE)) and under +commercial licenses. + +If you contribute on behalf of your employer, your employer may need to sign the Corporate CLA +instead. Contact info@thingsboard.io. diff --git a/application/pom.xml b/application/pom.xml index 05096269a8..1dcafd6e9c 100644 --- a/application/pom.xml +++ b/application/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard application diff --git a/application/src/main/data/upgrade/basic/schema_update.sql b/application/src/main/data/upgrade/basic/schema_update.sql deleted file mode 100644 index bb5bf9075a..0000000000 --- a/application/src/main/data/upgrade/basic/schema_update.sql +++ /dev/null @@ -1,10 +0,0 @@ --- --- SPDX-FileCopyrightText: Copyright The ThingsBoard Authors --- SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. --- SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 --- - --- Intentionally empty. The offline upgrade path is now fully bean-driven: every schema/data change lives in --- an LtsMigration bean and its data/upgrade/lts//schema_update.sql (4.4 baseline DDL is in --- V4_4_0_0Migration / lts/4.4.0.0/schema_update.sql). This file is kept present only so loadSql does not fail. - diff --git a/application/src/main/data/upgrade/lts/4.3.1.4/schema_update.sql b/application/src/main/data/upgrade/lts/4.3.1.4/schema_update.sql index 7478f25bdf..80d0654fcc 100644 --- a/application/src/main/data/upgrade/lts/4.3.1.4/schema_update.sql +++ b/application/src/main/data/upgrade/lts/4.3.1.4/schema_update.sql @@ -16,7 +16,7 @@ ALTER TABLE alarm_comment DROP CONSTRAINT IF EXISTS fk_alarm_comment_alarm_id; -- change (nullable, no default), so the ACCESS EXCLUSIVE lock it takes is released as soon as this -- migration transaction commits. -- --- The originator_id backfill for pre-existing rows is intentionally NOT done here. LtsMigrationService runs +-- The originator_id backfill for pre-existing rows is intentionally NOT done here. MigrationService runs -- this whole file inside a single transaction, so an in-line UPDATE would hold the ADD COLUMN's -- ACCESS EXCLUSIVE lock for the entire backfill -- blocking all reads and writes on entity_alarm while the -- no-downtime patch path (SystemPatchApplier) runs it on a serving node. Instead the backfill runs after diff --git a/application/src/main/data/upgrade/lts/4.4.0.0/schema_update.sql b/application/src/main/data/upgrade/lts/4.4.0.0/schema_update.sql index 4f84c6e011..9da79c3bad 100644 --- a/application/src/main/data/upgrade/lts/4.4.0.0/schema_update.sql +++ b/application/src/main/data/upgrade/lts/4.4.0.0/schema_update.sql @@ -14,9 +14,8 @@ ALTER TABLE rule_chain ADD COLUMN IF NOT EXISTS notes varchar(1000000); -- RULE CHAIN NOTES MIGRATION END --- PE-only 4.4 baseline DDL below (carried over from basic/schema_update.sql; these columns/index have no --- owning bean of their own). report.* live on the PE-only report table; job.customer_id is a PE column on the --- shared job table. +-- PE-only 4.4 baseline DDL below (these columns/index have no owning bean of their own). report.* live on +-- the PE-only report table; job.customer_id is a PE column on the shared job table. -- REPORT PUBLIC LINK ADDITION START diff --git a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java index 9d5f734bf4..a064a5bbaf 100644 --- a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java +++ b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java @@ -134,7 +134,7 @@ public class ThingsboardSecurityConfiguration { /** Session bootstrap, exempt for GET only: {@code POST} on the same path creates a custom menu. */ public static final String CUSTOM_MENU_ENTRY_POINT = "/api/customMenu"; public static final String ALLOWED_PERMISSIONS_ENTRY_POINT = "/api/permissions/allowedPermissions"; - protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[]{"/index.html", "/assets/**", "/static/**", "/api/noauth/**", "/webjars/**", "/api/license/**", "/api/images/public/**", "/api/v2/report/public/**", "/.well-known/**"}; + protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[]{"/index.html", "/assets/**", "/static/**", "/api/noauth/**", "/webjars/**", "/api/license/**", "/api/v2/license/**", "/api/images/public/**", "/api/v2/report/public/**", "/.well-known/**"}; /** * API entry points that stay reachable while the setup is incomplete, or while a provisioned instance is * locked again at runtime. Only {@link #SETUP_PROTECTED_ENTRY_POINTS} is locked, so the Angular diff --git a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java index 26c6a9fc54..af73926527 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java @@ -671,6 +671,35 @@ public class EdgeController extends BaseController { } } + @ApiOperation(value = "Check edge license (checkInstance)", + notes = "Checks license request (V1/V2) from edge service by forwarding request to license portal.") + @PostMapping(value = "/v2/license/checkInstance") + public ResponseEntity checkInstanceV2(@RequestBody JsonNode request) throws ThingsboardException { + log.debug("Checking instance [{}]", request); + try { + return edgeLicenseService.checkInstanceV2(request); + } catch (Exception e) { + log.error("Error occurred: [{}]", e.getMessage(), e); + throw new ThingsboardException(e, ThingsboardErrorCode.SUBSCRIPTION_VIOLATION); + } + } + + @ApiOperation(value = "Activate edge instance (activateInstance)", + notes = "Activates edge license (V1/V2) on license portal.") + @PostMapping(value = "/v2/license/activateInstance", params = {"licenseSecret", "releaseDate", "clusterId"}) + public ResponseEntity activateInstanceV2(@RequestParam String licenseSecret, + @RequestParam String releaseDate, + @RequestParam String clusterId, + @RequestParam(required = false) String protocolVersion) throws ThingsboardException { + log.debug("Activating instance [{}], [{}], [{}], [{}]", licenseSecret, releaseDate, clusterId, protocolVersion); + try { + return edgeLicenseService.activateInstanceV2(licenseSecret, releaseDate, clusterId, protocolVersion); + } catch (Exception e) { + log.error("Error occurred: [{}]", e.getMessage(), e); + throw new ThingsboardException(e, ThingsboardErrorCode.SUBSCRIPTION_VIOLATION); + } + } + private void cleanUpLicenseKey(Edge edge) { edge.setEdgeLicenseKey(null); } diff --git a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java index d9ffc7ba45..d6bdbab7eb 100644 --- a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java +++ b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.controller.plugin; import com.github.benmanes.caffeine.cache.Cache; @@ -19,6 +20,7 @@ import org.springframework.beans.factory.BeanCreationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; +import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Service; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.PongMessage; @@ -34,6 +36,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.limit.LimitedApi; +import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.config.WebSocketConfiguration; import org.thingsboard.server.dao.tenant.TbTenantProfileCache; @@ -56,6 +59,7 @@ import org.thingsboard.server.service.ws.telemetry.cmd.TelemetryCmdsWrapper; import java.io.IOException; import java.security.InvalidParameterException; +import java.util.EnumSet; import java.util.Optional; import java.util.Queue; import java.util.Set; @@ -77,6 +81,8 @@ import static org.thingsboard.server.service.ws.DefaultWebSocketService.NUMBER_O @RequiredArgsConstructor public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocketMsgEndpoint { + private static final Set USER_AUTHORITIES = EnumSet.of(Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER); + private final ConcurrentMap internalSessionMap = new ConcurrentHashMap<>(); private final ConcurrentMap externalSessionMap = new ConcurrentHashMap<>(); @@ -187,7 +193,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke if (StringUtils.isNotEmpty(authCmd.getApiKey())) { securityCtx = apiKeyAuthenticationProvider.authenticate(authCmd.getApiKey()); } else { - securityCtx = authenticationProvider.authenticate(authCmd.getToken()); + securityCtx = authenticate(authCmd.getToken()); } } catch (Exception e) { close(sessionRef, CloseStatus.BAD_DATA.withReason(e.getMessage())); @@ -326,7 +332,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke if (query != null) { String token = extractQueryParam(query, "token"); if (StringUtils.isNotEmpty(token)) { - securityCtx = authenticationProvider.authenticate(token); + securityCtx = authenticate(token); } } return WebSocketSessionRef.builder() @@ -347,6 +353,14 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke return null; } + private SecurityUser authenticate(String token) { + SecurityUser securityUser = authenticationProvider.authenticate(token); + if (!USER_AUTHORITIES.contains(securityUser.getAuthority())) { + throw new BadCredentialsException("Token is invalid"); + } + return securityUser; + } + private SessionMetaData getSessionMd(String internalSessionId) { SessionMetaData sessionMd = internalSessionMap.get(internalSessionId); if (sessionMd == null) { diff --git a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java index bf9b2d41d7..07d14417bd 100644 --- a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java +++ b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java @@ -114,7 +114,7 @@ public class ThingsboardInstallService { entityDatabaseSchemaService.createOrUpdateViewsAndFunctions(); entityDatabaseSchemaService.createOrUpdateDeviceInfoView(persistToTelemetry); } else { - // TODO DON'T FORGET to update SUPPORTED_VERSIONS_FOR_UPGRADE and MIN_CE_VERSION_FOR_UPGRADE in DefaultDatabaseSchemaSettingsService + // TODO DON'T FORGET to update SUPPORTED_FAMILIES_FOR_UPGRADE and MIN_CE_VERSION_FOR_UPGRADE in DefaultDatabaseSchemaSettingsService databaseSchemaVersionService.validateSchemaSettings(); // The database's own product marker selects the branch, so a CE database can never be taken // down the PE path by a missing flag. --fromVersion=CE is still accepted, and now a no-op. @@ -131,7 +131,7 @@ public class ThingsboardInstallService { } cacheCleanupService.clearCache(); if (updateFromCE) { - // The LTS chain references PE-only tables and runs each of its files as a single transaction, + // The migration chain references PE-only tables and runs each of its files as a single transaction, // so a converted CE database must get those tables before the chain rather than after it. entityDatabaseSchemaService.createDatabaseSchema(false); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java b/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java index 9186e307dd..45263ef7fd 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java @@ -66,7 +66,7 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService { new HttpEntity<>(request, headers), JsonNode.class); log.trace("checkInstance response: {}", response); // removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections - return new ResponseEntity(response.getBody(), response.getStatusCode()); + return new ResponseEntity<>(response.getBody(), response.getStatusCode()); } @Override @@ -80,7 +80,38 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService { null, JsonNode.class, params); log.trace("activateInstance response: {}", response); // removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections - return new ResponseEntity(response.getBody(), response.getStatusCode()); + return new ResponseEntity<>(response.getBody(), response.getStatusCode()); + } + + @Override + public ResponseEntity checkInstanceV2(JsonNode request) { + log.trace("checkInstance V2 [{}]", request); + var headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + ResponseEntity response = this.restTemplate.postForEntity( + EDGE_LICENSE_SERVER_ENDPOINT + "/api/v2/license/checkInstance", + new HttpEntity<>(request, headers), JsonNode.class); + log.trace("checkInstance V2 response: {}", response); + // removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections + return new ResponseEntity<>(response.getBody(), response.getStatusCode()); + } + + @Override + public ResponseEntity activateInstanceV2(String edgeLicenseSecret, String releaseDate, String clusterId, String protocolVersion) { + log.trace("activateInstance V2 [{}][{}][{}]", releaseDate, clusterId, protocolVersion); + Map params = new HashMap<>(); + params.put("licenseSecret", edgeLicenseSecret); + params.put("releaseDate", releaseDate); + params.put("clusterId", clusterId); + String url = EDGE_LICENSE_SERVER_ENDPOINT + "/api/v2/license/activateInstance?licenseSecret={licenseSecret}&releaseDate={releaseDate}&clusterId={clusterId}"; + if (protocolVersion != null) { + params.put("protocolVersion", protocolVersion); + url += "&protocolVersion={protocolVersion}"; + } + ResponseEntity response = this.restTemplate.postForEntity(url, null, JsonNode.class, params); + log.trace("activateInstance V2 response: {}", response); + // removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections + return new ResponseEntity<>(response.getBody(), response.getStatusCode()); } private RestTemplate initRestTemplate() { diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeLicenseService.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeLicenseService.java index 0f2ca9dccf..bc796b02b1 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeLicenseService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeLicenseService.java @@ -10,4 +10,8 @@ public interface EdgeLicenseService { ResponseEntity checkInstance(JsonNode request); ResponseEntity activateInstance(String licenseSecret, String releaseDate); + + ResponseEntity checkInstanceV2(JsonNode request); + + ResponseEntity activateInstanceV2(String licenseSecret, String releaseDate, String clusterId, String protocolVersion); } diff --git a/application/src/main/java/org/thingsboard/server/service/install/DatabaseSchemaSettingsService.java b/application/src/main/java/org/thingsboard/server/service/install/DatabaseSchemaSettingsService.java index 5d4a09d9a2..dbfb1d17cd 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/DatabaseSchemaSettingsService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/DatabaseSchemaSettingsService.java @@ -9,7 +9,7 @@ public interface DatabaseSchemaSettingsService { /** * Whether the operator forced this offline upgrade past the version check (SKIP_SCHEMA_VERSION_CHECK). Besides - * suppressing the validation errors, it makes the LTS migration selection inclusive of the stored version, so a + * suppressing the validation errors, it makes the migration selection inclusive of the stored version, so a * database already at the package version re-runs that version's own migration instead of selecting nothing. */ boolean isForcedReUpgrade(); diff --git a/application/src/main/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsService.java b/application/src/main/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsService.java index 496d9296a8..35fb27aed7 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsService.java @@ -7,27 +7,24 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; -import org.thingsboard.server.service.install.lts.LtsVersion; +import org.thingsboard.server.service.install.lts.Version; import org.thingsboard.server.service.install.update.DefaultDataUpdateService; -import java.util.Map; +import java.util.List; @Service @Slf4j @RequiredArgsConstructor public class DefaultDatabaseSchemaSettingsService implements DatabaseSchemaSettingsService { - // map of versions from which the upgrade to the current version is possible - // key - supported version prefix, value - display name - private static final Map SUPPORTED_VERSIONS_FOR_UPGRADE = Map.of( - "4.3.0", "4.3.0.x", - "4.3.1", "4.3.1.x" - ); + // LTS families (major.minor) from which the offline upgrade to the current version is possible. A newer version + // within the package's own family needs no offline upgrade: SystemPatchApplier applies it on startup. + private static final List SUPPORTED_FAMILIES_FOR_UPGRADE = List.of(Version.parse("4.3")); private static final String CE_PRODUCT = "CE"; // The first CE version that converts to PE: the one that ships the community grant. Anything older takes the // cheap CE-to-CE patch upgrade first. 4.3 stays supported, so later 4.3.1.x releases convert as well. - private static final LtsVersion MIN_CE_VERSION_FOR_UPGRADE = LtsVersion.parse("4.3.1.4"); + private static final Version MIN_CE_VERSION_FOR_UPGRADE = Version.parse("4.3.1.6"); private final ProjectInfo projectInfo; private final JdbcTemplate jdbcTemplate; @@ -37,8 +34,8 @@ public class DefaultDatabaseSchemaSettingsService implements DatabaseSchemaSetti @Override public void validateSchemaSettings() { - // The flag also drops the CE floor below, and that is what it costs: the 4.3.1.4 minimum is - // what keeps a CE source above 4.2.2.3, and so keeps LtsMigrationService.select() from ever returning + // The flag also drops the CE floor below, and that is what it costs: the CE minimum is + // what keeps a CE source above 4.2.2.3, and so keeps MigrationService.select() from ever returning // the V4_2_2_3 <-> V4_3_1_3 reproduction-duplicate pair its own invariant forbids selecting together. // Forcing an older CE database through without --fromVersion reopens that pair. if (isForcedReUpgrade()) { @@ -48,7 +45,7 @@ public class DefaultDatabaseSchemaSettingsService implements DatabaseSchemaSetti String dbSchemaVersion = getDbSchemaVersion(); if (isUpgradeFromCe()) { - LtsVersion ceVersion = LtsVersion.parse(dbSchemaVersion); + Version ceVersion = Version.parse(dbSchemaVersion); if (ceVersion.compareTo(MIN_CE_VERSION_FOR_UPGRADE) < 0) { onSchemaSettingsError(String.format("Upgrade failed: transitioning from CE to PE requires the database to be at version '%s' or newer, but it is at '%s'. " + "Please upgrade ThingsBoard CE to %s first.", @@ -56,7 +53,7 @@ public class DefaultDatabaseSchemaSettingsService implements DatabaseSchemaSetti } // Without this the migration chain would select nothing and the PE schema would be created on top of a // newer CE database, silently. - if (ceVersion.compareTo(LtsVersion.parse(getPackageSchemaVersion())) > 0) { + if (ceVersion.compareTo(Version.parse(getPackageSchemaVersion())) > 0) { onSchemaSettingsError(String.format("Upgrade failed: the database is at CE version '%s', which is newer than this ThingsBoard PE package ('%s'). " + "Please use a PE package of version '%s' or newer.", dbSchemaVersion, getPackageSchemaVersion(), dbSchemaVersion)); @@ -66,10 +63,16 @@ public class DefaultDatabaseSchemaSettingsService implements DatabaseSchemaSetti onSchemaSettingsError("Upgrade failed: database already upgraded to current version. You can set SKIP_SCHEMA_VERSION_CHECK to 'true' if force re-upgrade needed."); } - if (SUPPORTED_VERSIONS_FOR_UPGRADE.keySet().stream().noneMatch(dbSchemaVersion::startsWith)) { + Version dbVersion = Version.parse(dbSchemaVersion); + Version packageVersion = Version.parse(getPackageSchemaVersion()); + if (dbVersion.sameFamily(packageVersion) && dbVersion.compareTo(packageVersion) < 0) { + onSchemaSettingsError(String.format("Upgrade failed: database version '%s' is in the same LTS family as this package ('%s'). " + + "No upgrade is needed: the update is applied automatically when ThingsBoard starts.", + dbSchemaVersion, getPackageSchemaVersion())); + } + if (SUPPORTED_FAMILIES_FOR_UPGRADE.stream().noneMatch(dbVersion::sameFamily)) { onSchemaSettingsError(String.format("Upgrade failed: database version '%s' is not supported for upgrade. Supported versions are: %s.", - dbSchemaVersion, SUPPORTED_VERSIONS_FOR_UPGRADE.values() - )); + dbSchemaVersion, SUPPORTED_FAMILIES_FOR_UPGRADE.stream().map(f -> f.major() + "." + f.minor() + ".x").toList())); } } } @@ -159,7 +162,7 @@ public class DefaultDatabaseSchemaSettingsService implements DatabaseSchemaSetti } private long toDbVersion(String version) { - LtsVersion v = LtsVersion.parse(version); + Version v = Version.parse(version); return v.major() * 1_000_000_000L + v.minor() * 1_000_000L + v.maintenance() * 1000L + v.patch(); } @@ -169,7 +172,7 @@ public class DefaultDatabaseSchemaSettingsService implements DatabaseSchemaSetti } private String normalizeVersion(String version) { - return LtsVersion.parse(version).toString(); + return Version.parse(version).toString(); } } diff --git a/application/src/main/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeService.java b/application/src/main/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeService.java index b7a75e407c..12e0f624a2 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeService.java @@ -11,7 +11,7 @@ import org.springframework.jdbc.core.StatementCallback; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; -import org.thingsboard.server.service.install.lts.LtsMigrationService; +import org.thingsboard.server.service.install.lts.MigrationService; import java.io.IOException; import java.io.UncheckedIOException; @@ -32,18 +32,18 @@ public class SqlDatabaseUpgradeService implements DatabaseEntitiesUpgradeService private final JdbcTemplate jdbcTemplate; private final TransactionTemplate transactionTemplate; private final DatabaseSchemaSettingsService schemaSettingsService; - private final LtsMigrationService ltsMigrationService; + private final MigrationService migrationService; public SqlDatabaseUpgradeService(InstallScripts installScripts, JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager, DatabaseSchemaSettingsService schemaSettingsService, - LtsMigrationService ltsMigrationService) { + MigrationService migrationService) { this.installScripts = installScripts; this.jdbcTemplate = jdbcTemplate; this.transactionTemplate = new TransactionTemplate(transactionManager); this.transactionTemplate.setTimeout((int) TimeUnit.MINUTES.toSeconds(120)); this.schemaSettingsService = schemaSettingsService; - this.ltsMigrationService = ltsMigrationService; + this.migrationService = migrationService; } @Override @@ -51,12 +51,11 @@ public class SqlDatabaseUpgradeService implements DatabaseEntitiesUpgradeService log.info("Updating schema..."); if (fromCe) { // The delta is not confined to the version the database is already at - it also carries package-version - // DDL that the LTS chain below adds again (the job.customer_id and tb_cluster columns, for instance). + // DDL that the migration chain below adds again (the job.customer_id and tb_cluster columns, for instance). // Running it first is safe because every statement in it is repeat-safe, not because it is version-scoped. loadSql(getSchemaUpdateFile("pe")); } - loadSql(getSchemaUpdateFile("basic")); - ltsMigrationService.runSchemaMigrations(schemaSettingsService.getDbSchemaVersion(), schemaSettingsService.getPackageSchemaVersion(), + migrationService.runSchemaMigrations(schemaSettingsService.getDbSchemaVersion(), schemaSettingsService.getPackageSchemaVersion(), schemaSettingsService.isForcedReUpgrade()); log.info("Schema updated."); } diff --git a/application/src/main/java/org/thingsboard/server/service/install/TbClusterSchema.java b/application/src/main/java/org/thingsboard/server/service/install/TbClusterSchema.java index d07263af62..c9118894e7 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/TbClusterSchema.java +++ b/application/src/main/java/org/thingsboard/server/service/install/TbClusterSchema.java @@ -4,7 +4,7 @@ package org.thingsboard.server.service.install; /** * The statements that reach {@code tb_cluster} from Java. The DDL is a hand-kept copy of the block in - * {@code schema-entities.sql}; {@code LtsMigrationIntegrationTest} pins the copies against it. + * {@code schema-entities.sql}; {@code MigrationIntegrationTest} pins the copies against it. */ public final class TbClusterSchema { diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/Migration.java similarity index 80% rename from application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigration.java rename to application/src/main/java/org/thingsboard/server/service/install/lts/Migration.java index 85f1b95b3d..9c60ab7d74 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/Migration.java @@ -4,12 +4,12 @@ package org.thingsboard.server.service.install.lts; /** - * One LTS migration, keyed by the version it ships in (e.g. "4.2.2.3"). + * One migration, keyed by the version it ships in (e.g. "4.2.2.3"). * The runner runs the version's data/upgrade/lts/<version>/schema_update.sql by convention * (if present), then calls {@link #apply()} for any programmatic work beyond SQL. * Most migrations are SQL-only and only override {@link #getVersion()}. *

- * Ordering caveat for a multi-version run (see {@link LtsMigrationService#applyMigrations}): on the no-downtime path + * Ordering caveat for a multi-version run (see {@link MigrationService#applyMigrations}): on the no-downtime path * every migration's schema_update.sql + {@link #apply()} runs, in version order, BEFORE any migration's * {@link #applyAfterCommit()}. So migration N+1's schema/apply executes ahead of migration N's backfill. A migration * must therefore not depend, in its schema_update.sql or {@link #apply()}, on the completed result of an earlier @@ -20,13 +20,13 @@ package org.thingsboard.server.service.install.lts; * {@link #applyAfterCommit()} must therefore tolerate the schema changes of every later migration in the same run -- * equivalently, later DDL must not drop, rename, or retype anything an earlier migration's backfill reads or writes. */ -public interface LtsMigration { +public interface Migration { String getVersion(); /** * Programmatic data migration that runs in the SAME transaction as the version's schema_update.sql - * (see {@link LtsMigrationService#applyMigrations}). Use for work that must be atomic with the schema + * (see {@link MigrationService#applyMigrations}). Use for work that must be atomic with the schema * change. Do NOT put heavy table rewrites here: on the no-downtime path the schema_update.sql DDL holds * its locks until this transaction commits, so a long apply() keeps those locks held while the node serves. *

@@ -38,13 +38,13 @@ public interface LtsMigration { /** * Programmatic data migration that runs AFTER the version's schema transaction has committed, outside any - * transaction (see {@link LtsMigrationService#applyMigrations} and {@link LtsMigrationService#runDataMigrations}). + * transaction (see {@link MigrationService#applyMigrations} and {@link MigrationService#runDataMigrations}). * Use for heavy or long-running data backfills that must not extend the lifetime of the schema-change locks: * the implementation is responsible for chunking the work into its own small, self-committing transactions so * it only ever holds row-level locks and never blocks concurrent readers/writers. *

- * Must be idempotent and resumable: {@link LtsMigrationService#applyMigrations} does not record the version - * itself, and the caller records it (see {@link LtsMigrationService#recordVersions}) only once whatever it + * Must be idempotent and resumable: {@link MigrationService#applyMigrations} does not record the version + * itself, and the caller records it (see {@link MigrationService#recordVersions}) only once whatever it * needs after this method returns has also succeeded. A crash, or that later failure, before the version is * recorded selects the migration again on the next startup and runs this method again from the start -- it * must skip already-migrated rows rather than redo or double-count them. diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java b/application/src/main/java/org/thingsboard/server/service/install/lts/MigrationService.java similarity index 81% rename from application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java rename to application/src/main/java/org/thingsboard/server/service/install/lts/MigrationService.java index bfc045457a..b4f3908dec 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/MigrationService.java @@ -24,10 +24,10 @@ import java.util.List; import java.util.Set; /** - * Applies {@link LtsMigration} beans (in version order) for an LTS upgrade. Each migration has up to four idempotent + * Applies {@link Migration} beans (in version order) for an upgrade. Each migration has up to four idempotent * parts: (1) its {@code schema_update.sql} DDL, run via {@link #executeSchemaSql} (absent file = no-op); (2) - * {@link LtsMigration#apply()}, schema-coupled changes that must be atomic with the DDL; (3) - * {@link LtsMigration#applyAfterCommit()}, the heavy backfill, run outside the DDL transaction and self-committing in + * {@link Migration#apply()}, schema-coupled changes that must be atomic with the DDL; (3) + * {@link Migration#applyAfterCommit()}, the heavy backfill, run outside the DDL transaction and self-committing in * chunks; and (4) recording the version, which callers must delay until (2) and (3) -- and anything else they * interpose -- have succeeded (see {@link #recordVersions}). *

@@ -42,7 +42,7 @@ import java.util.Set; *

  • Offline major upgrade -- runs in the install/upgrade process (node not serving), split across that * process's schema and data phases: {@link #runSchemaMigrations} (DDL only) runs with the rest of the schema * upgrade, then {@link #runDataMigrations} (apply() + backfill) runs later, after the install flow has created the - * new tables, views/functions and indexes the data migrations may depend on. Neither records the LTS version; the + * new tables, views/functions and indexes the data migrations may depend on. Neither records the migration version; the * offline upgrade flow tracks the package version itself.
  • * *

    @@ -56,12 +56,12 @@ import java.util.Set; @Slf4j @Component @TbCoreComponent -public class LtsMigrationService { +public class MigrationService { private static final String SCHEMA_UPDATE_SQL = "schema_update.sql"; /** A migration paired with its parsed version, so the version is parsed exactly once per bean. */ - private record VersionedMigration(LtsVersion version, LtsMigration migration) {} + private record VersionedMigration(Version version, Migration migration) {} private final JdbcTemplate jdbcTemplate; private final InstallScripts installScripts; @@ -69,27 +69,27 @@ public class LtsMigrationService { private final TransactionTemplate transactionTemplate; private final List migrations; - public LtsMigrationService(JdbcTemplate jdbcTemplate, - InstallScripts installScripts, - DatabaseSchemaSettingsService schemaSettingsService, - PlatformTransactionManager transactionManager, - List migrations) { + public MigrationService(JdbcTemplate jdbcTemplate, + InstallScripts installScripts, + DatabaseSchemaSettingsService schemaSettingsService, + PlatformTransactionManager transactionManager, + List migrations) { this.jdbcTemplate = jdbcTemplate; this.installScripts = installScripts; this.schemaSettingsService = schemaSettingsService; this.transactionTemplate = new TransactionTemplate(transactionManager); this.migrations = validateAndSort(migrations); - log.info("Discovered {} LTS migration(s): {}", this.migrations.size(), + log.info("Discovered {} migration(s): {}", this.migrations.size(), this.migrations.stream().map(versionedMigration -> versionedMigration.migration().getVersion()).toList()); } - private static List validateAndSort(List migrations) { + private static List validateAndSort(List migrations) { Set seen = new HashSet<>(); List versioned = new ArrayList<>(); - for (LtsMigration migration : migrations) { - LtsVersion version = LtsVersion.parse(migration.getVersion()); // fail loud on unparseable version + for (Migration migration : migrations) { + Version version = Version.parse(migration.getVersion()); // fail loud on unparseable version if (!seen.add(migration.getVersion())) { - throw new IllegalStateException("Duplicate LTS migration version: " + migration.getVersion()); + throw new IllegalStateException("Duplicate migration version: " + migration.getVersion()); } versioned.add(new VersionedMigration(version, migration)); } @@ -110,17 +110,17 @@ public class LtsMigrationService { public List applyMigrations(String fromVersion, String toVersion, boolean forcedRun, Runnable afterSchemaPhase) { List selected = select(fromVersion, toVersion, forcedRun); for (VersionedMigration versionedMigration : selected) { - LtsMigration migration = versionedMigration.migration(); + Migration migration = versionedMigration.migration(); transactionTemplate.executeWithoutResult(status -> { executeSchemaSql(migration.getVersion()); migration.apply(); }); - log.info("Applied LTS schema update {}", migration.getVersion()); + log.info("Applied schema update {}", migration.getVersion()); } afterSchemaPhase.run(); List appliedVersions = new ArrayList<>(); for (VersionedMigration versionedMigration : selected) { - LtsMigration migration = versionedMigration.migration(); + Migration migration = versionedMigration.migration(); migration.applyAfterCommit(); // outside the schema transaction (see class doc) appliedVersions.add(migration.getVersion()); } @@ -130,12 +130,12 @@ public class LtsMigrationService { /** * Records the versions {@link #applyMigrations} returned, once the caller's own post-schema work has succeeded. * Stamped together rather than one per backfill, so a later failure re-runs the earlier migrations' backfills on - * the next startup - which {@link LtsMigration#applyAfterCommit} is required to tolerate. + * the next startup - which {@link Migration#applyAfterCommit} is required to tolerate. */ public void recordVersions(List versions) { for (String version : versions) { schemaSettingsService.updateSchemaVersion(version); - log.info("Applied LTS migration {}", version); + log.info("Applied migration {}", version); } } @@ -150,7 +150,7 @@ public class LtsMigrationService { for (VersionedMigration versionedMigration : select(fromVersion, toVersion, forcedRun)) { String version = versionedMigration.migration().getVersion(); transactionTemplate.executeWithoutResult(status -> executeSchemaSql(version)); - log.info("Applied LTS schema migration {}", version); + log.info("Applied schema migration {}", version); } } @@ -163,16 +163,16 @@ public class LtsMigrationService { */ public void runDataMigrations(String fromVersion, String toVersion, boolean forcedRun) { for (VersionedMigration versionedMigration : select(fromVersion, toVersion, forcedRun)) { - LtsMigration migration = versionedMigration.migration(); + Migration migration = versionedMigration.migration(); migration.apply(); migration.applyAfterCommit(); - log.info("Applied LTS data migration {}", migration.getVersion()); + log.info("Applied data migration {}", migration.getVersion()); } } private List select(String fromVersion, String toVersion, boolean forcedRun) { - LtsVersion from = LtsVersion.parse(fromVersion); - LtsVersion to = LtsVersion.parse(toVersion); + Version from = Version.parse(fromVersion); + Version to = Version.parse(toVersion); // Select every migration in the (from, to] range, regardless of family. On a cross-family offline // upgrade (e.g. 4.3.x -> 4.4) this is what makes the real in-range older-family beans run: it picks the // 4.3.1.x schema/data changes the source has not yet passed AND the new target-family beans, each exactly @@ -184,8 +184,8 @@ public class LtsMigrationService { // range. A reproduction-duplicate bean (one that re-does an older bean's work on a newer-family branch) // must sit STRICTLY BELOW the minimum supported upgrade source, so it can never be selected together with // the bean it duplicates. The pairs today are 4.2.2.3 <-> 4.3.1.3 and 4.2.2.4 <-> 4.3.1.4, and the - // supported-source floor is 4.3.0.0 (SUPPORTED_VERSIONS_FOR_UPGRADE), well above both 4.2.2.x beans. - // LtsMigrationServiceTest guards this. + // supported-source floor is 4.3.0.0 (SUPPORTED_FAMILIES_FOR_UPGRADE), well above both 4.2.2.x beans. + // MigrationServiceTest guards this. // // A forced run takes the closed [from, to] instead, so the source version's own migration re-runs rather than // the range being empty -- see the class doc. It does not weaken that invariant in any new way: forcing @@ -202,14 +202,14 @@ public class LtsMigrationService { private void executeSchemaSql(String version) { Path sqlFile = Paths.get(installScripts.getDataDir(), "upgrade", "lts", version, SCHEMA_UPDATE_SQL); if (!Files.exists(sqlFile)) { - log.trace("No LTS schema update file for version {} at {}", version, sqlFile); + log.trace("No schema update file for version {} at {}", version, sqlFile); return; } try { jdbcTemplate.execute(Files.readString(sqlFile)); - log.info("Applied LTS SQL schema update from {}", sqlFile); + log.info("Applied SQL schema update from {}", sqlFile); } catch (IOException e) { - throw new UncheckedIOException("Failed to read LTS schema update file: " + sqlFile, e); + throw new UncheckedIOException("Failed to read schema update file: " + sqlFile, e); } } } diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_2_2_3Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_2_2_3Migration.java index 4421b6ee41..ca46ee5e14 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_2_2_3Migration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_2_2_3Migration.java @@ -39,7 +39,7 @@ import java.util.stream.Stream; @Component @TbCoreComponent @RequiredArgsConstructor -public class V4_2_2_3Migration implements LtsMigration { +public class V4_2_2_3Migration implements Migration { // Match on the bundle ALIAS, not the JSON filename stem. // The "industrial_widgets" bundle shipped in a misspelled file (industial_widgets.json), diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_2Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_2Migration.java index 3593d99b64..7b50027d35 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_2Migration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_2Migration.java @@ -9,18 +9,18 @@ import org.thingsboard.server.queue.util.TbCoreComponent; /** * Registration-only migration with no {@link #apply()} (no data migration), kept intentionally. *

    - * {@link LtsMigrationService} selects migrations from the injected {@link LtsMigration} beans, not from the + * {@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.3.1.2} and execute its {@code data/upgrade/lts/4.3.1.2/schema_update.sql} (which adds the * 4.3.1.2 columns: {@code api_usage_state.ai}, {@code calculated_field.additional_info}, * {@code role.excluded_permissions}, {@code tb_user.external_id} plus the {@code tb_user_external_id_unq_key} * constraint). A directory holding a {@code schema_update.sql} but lacking a matching bean would be silently skipped. *

    - * The dir/bean consistency (both ways) is guarded by a test in {@code LtsMigrationIntegrationTest}. + * The dir/bean consistency (both ways) is guarded by a test in {@code MigrationIntegrationTest}. */ @Component @TbCoreComponent -public class V4_3_1_2Migration implements LtsMigration { +public class V4_3_1_2Migration implements Migration { @Override public String getVersion() { diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_3Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_3Migration.java index 7cfa8c7332..2491a34c3b 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_3Migration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_3Migration.java @@ -42,7 +42,7 @@ import java.util.stream.Stream; @Component @TbCoreComponent @RequiredArgsConstructor -public class V4_3_1_3Migration implements LtsMigration { +public class V4_3_1_3Migration implements Migration { // Match on the bundle ALIAS, not the JSON filename stem. // The "industrial_widgets" bundle shipped in a misspelled file (industial_widgets.json), @@ -77,7 +77,7 @@ public class V4_3_1_3Migration implements LtsMigration { @Override public void applyAfterCommit() { // Heavy per-tenant backfill: runs outside the schema transaction so it never holds the schema-change - // locks while walking tenants (see LtsMigration#applyAfterCommit). + // locks while walking tenants (see Migration#applyAfterCommit). migrateLegacySolutionTemplatesToIotHub(); } diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_4Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_4Migration.java index 264b52f056..b796a1ecd7 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_4Migration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_4Migration.java @@ -17,7 +17,7 @@ import java.util.UUID; /** * Alarm sharding: drops the {@code alarm_comment -> alarm} cascade FK and adds {@code entity_alarm.originator_id}. *

    - * {@link LtsMigrationService} selects migrations from the injected {@link LtsMigration} beans, not from the on-disk + * {@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.3.1.4} and execute its {@code schema_update.sql} at all. *

    @@ -34,7 +34,7 @@ import java.util.UUID; @Slf4j @Component @TbCoreComponent -public class V4_3_1_4Migration implements LtsMigration { +public class V4_3_1_4Migration implements Migration { // entity_alarm is walked in keyset-paginated windows of this size, each in its own committed transaction, so // the backfill only ever holds row-level locks on the current window and never blocks concurrent readers. @@ -86,7 +86,7 @@ public class V4_3_1_4Migration implements LtsMigration { /** * Backfills entity_alarm.originator_id from the parent alarm for rows that predate the column added by this - * version's schema_update.sql. Runs OUTSIDE the schema transaction (see {@link LtsMigration#applyAfterCommit}) + * version's schema_update.sql. Runs OUTSIDE the schema transaction (see {@link Migration#applyAfterCommit}) * so the ADD COLUMN's ACCESS EXCLUSIVE lock is already released; each batch commits on its own and takes only * a ROW EXCLUSIVE lock, so a serving node keeps reading and writing entity_alarm throughout. *

    diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_5Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_5Migration.java index 3642e23c41..87361ff51d 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_5Migration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_5Migration.java @@ -22,14 +22,14 @@ import java.util.Set; import static org.thingsboard.server.dao.trendz.TrendzSyncService.TRENDZ_API_KEY_DESCRIPTION; /** - * LTS migration for version {@code 4.3.1.5}. + * Migration for version {@code 4.3.1.5}. *

    - * {@link LtsMigrationService} selects migrations from the injected {@link LtsMigration} beans, not from the on-disk + * {@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.3.1.5} at all. *

    * There is no {@code data/upgrade/lts/4.3.1.5/} directory: everything this version changes is programmatic, so the - * version is listed in {@code SQL_LESS_ALLOWED} in {@code LtsMigrationIntegrationTest}, which otherwise fails a bean + * version is listed in {@code SQL_LESS_ALLOWED} in {@code MigrationIntegrationTest}, which otherwise fails a bean * that has no matching directory. Should this version later need DDL, add the directory and drop that entry. *

    * Each thing this version migrates lives in its own private method called from {@link #apply()}, with the constants @@ -39,7 +39,7 @@ import static org.thingsboard.server.dao.trendz.TrendzSyncService.TRENDZ_API_KEY @Component @TbCoreComponent @RequiredArgsConstructor -public class V4_3_1_5Migration implements LtsMigration { +public class V4_3_1_5Migration implements Migration { private final ApiKeyService apiKeyService; @@ -50,7 +50,7 @@ public class V4_3_1_5Migration implements LtsMigration { /** * Runs in the same transaction as the version's schema SQL on the no-downtime path, and outside any transaction - * on the offline path (see {@link LtsMigration#apply}). Every step below must therefore be light enough to sit in + * on the offline path (see {@link Migration#apply}). Every step below must therefore be light enough to sit in * a schema transaction, and idempotent, since a crash before the version is recorded re-runs it. */ @Override diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java index 1756033ef1..434394b586 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java @@ -20,7 +20,7 @@ import java.util.UUID; @Component @TbCoreComponent @RequiredArgsConstructor -public class V4_3_1_6Migration implements LtsMigration { +public class V4_3_1_6Migration implements Migration { private final JdbcTemplate jdbcTemplate; diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_0_0Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_0_0Migration.java index a9e4b47e05..3341520dd1 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_0_0Migration.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_0_0Migration.java @@ -19,30 +19,30 @@ import java.util.UUID; * Registration-only migration with no {@link #apply()} (no data migration), plus an {@link #applyAfterCommit()} * backfill that closes the pre-existing legacy stuck-RPC backlog. *

    - * {@link LtsMigrationService} selects migrations from the injected {@link LtsMigration} beans, not from the + * {@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.0.0} and execute its {@code data/upgrade/lts/4.4.0.0/schema_update.sql}, which -- among the * other 4.4 changes -- adds the nullable {@code rpc.request_id} and {@code rpc.oneway} columns. *

    * The RPC change rides the {@code 4.4.0.0} slot rather than a 4.3/4.2-family one because it ships in 4.4 only. * {@code 4.3.1.4} is already released (and, in PE, already carries the {@code entity_alarm.originator_id} - * backfill), and {@link LtsVersion#isInRange} is exclusive at the lower bound -- so an installation already on + * backfill), and {@link Version#isInRange} is exclusive at the lower bound -- so an installation already on * {@code 4.3.1.4} would never re-run that version. Every supported upgrade source ({@code 4.3.0.x}, * {@code 4.3.1.x}) is below {@code 4.4.0.0}, so all of them select this migration exactly once. *

    - * The dir/bean consistency (both ways) is guarded by a test in {@code LtsMigrationIntegrationTest}. + * The dir/bean consistency (both ways) is guarded by a test in {@code MigrationIntegrationTest}. *

    * {@link #applyAfterCommit()} closes rows left stuck by earlier server versions that predate {@code request_id} * tracking: any {@code rpc} row with {@code request_id IS NULL} that is past its expiration and still sitting in * {@code SENT} or {@code TIMEOUT}, or in {@code DELIVERED} for a two-way call (one-way {@code DELIVERED} is already terminal * success), is force-closed to {@code EXPIRED} with a canned response. It walks the {@code rpc} table by primary * key in keyset-paginated, self-committing batches so it never holds a long transaction or blocks concurrent - * readers/writers; see the class-level backfill contract on {@link LtsMigration#applyAfterCommit()}. + * readers/writers; see the class-level backfill contract on {@link Migration#applyAfterCommit()}. */ @Slf4j @Component @TbCoreComponent -public class V4_4_0_0Migration implements LtsMigration { +public class V4_4_0_0Migration implements Migration { // Same wording as DeviceActorMessageProcessor.LEGACY_UNTRACKED_MESSAGE, so a row closed by this one-time // backfill reads identically to one closed live by the actor on reload. diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java b/application/src/main/java/org/thingsboard/server/service/install/lts/Version.java similarity index 80% rename from application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java rename to application/src/main/java/org/thingsboard/server/service/install/lts/Version.java index a46c556095..7abf7c3420 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/Version.java @@ -3,9 +3,9 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.install.lts; -public record LtsVersion(int major, int minor, int maintenance, int patch) implements Comparable { +public record Version(int major, int minor, int maintenance, int patch) implements Comparable { - public static LtsVersion parse(String version) { + public static Version parse(String version) { if (version == null) { throw new IllegalArgumentException("Version is null"); } @@ -15,13 +15,13 @@ public record LtsVersion(int major, int minor, int maintenance, int patch) imple int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; int maintenance = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; int patch = parts.length > 3 ? Integer.parseInt(parts[3]) : 0; - return new LtsVersion(major, minor, maintenance, patch); + return new Version(major, minor, maintenance, patch); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid version: " + version, e); } } - public boolean sameFamily(LtsVersion other) { + public boolean sameFamily(Version other) { return major == other.major && minor == other.minor; } @@ -29,20 +29,20 @@ public record LtsVersion(int major, int minor, int maintenance, int patch) imple * Half-open range check: {@code from < this <= to}. The lower bound is exclusive (a source already at * {@code from} has applied that version) and the upper bound inclusive (the target version's own migration runs). */ - public boolean isInRange(LtsVersion from, LtsVersion to) { + public boolean isInRange(Version from, Version to) { return compareTo(from) > 0 && compareTo(to) <= 0; } /** * Closed range check: {@code from <= this <= to}. Only for a run an operator has forced past its version check, - * where the source's own migration has to be re-run (see {@link LtsMigrationService}). + * where the source's own migration has to be re-run (see {@link MigrationService}). */ - public boolean isInClosedRange(LtsVersion from, LtsVersion to) { + public boolean isInClosedRange(Version from, Version to) { return compareTo(from) >= 0 && compareTo(to) <= 0; } @Override - public int compareTo(LtsVersion o) { + public int compareTo(Version o) { int c = Integer.compare(major, o.major); if (c != 0) { return c; diff --git a/application/src/main/java/org/thingsboard/server/service/install/update/DefaultDataUpdateService.java b/application/src/main/java/org/thingsboard/server/service/install/update/DefaultDataUpdateService.java index e01e9b92b5..eb9ddb2c6a 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/update/DefaultDataUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/update/DefaultDataUpdateService.java @@ -55,7 +55,7 @@ import org.thingsboard.server.service.component.RuleNodeClassInfo; import org.thingsboard.server.service.install.DatabaseSchemaSettingsService; import org.thingsboard.server.service.install.DbUpgradeExecutorService; import org.thingsboard.server.service.install.SystemDataLoaderService; -import org.thingsboard.server.service.install.lts.LtsMigrationService; +import org.thingsboard.server.service.install.lts.MigrationService; import org.thingsboard.server.utils.TbNodeUpgradeUtils; import java.lang.reflect.Field; @@ -99,7 +99,7 @@ public class DefaultDataUpdateService implements DataUpdateService { private final ComponentDiscoveryService componentDiscoveryService; private final DbUpgradeExecutorService executorService; private final DatabaseSchemaSettingsService schemaSettingsService; - private final LtsMigrationService ltsMigrationService; + private final MigrationService migrationService; @Override public void updateData(boolean fromCe) throws Exception { @@ -109,7 +109,7 @@ public class DefaultDataUpdateService implements DataUpdateService { } //TODO: should be cleaned after each release backfillForExistingTenants(); - ltsMigrationService.runDataMigrations(schemaSettingsService.getDbSchemaVersion(), schemaSettingsService.getPackageSchemaVersion(), + migrationService.runDataMigrations(schemaSettingsService.getDbSchemaVersion(), schemaSettingsService.getPackageSchemaVersion(), schemaSettingsService.isForcedReUpgrade()); log.info("Data updated."); } diff --git a/application/src/main/java/org/thingsboard/server/service/report/LocalReportDataService.java b/application/src/main/java/org/thingsboard/server/service/report/LocalReportDataService.java index 1ba1f1aace..23c96858c8 100644 --- a/application/src/main/java/org/thingsboard/server/service/report/LocalReportDataService.java +++ b/application/src/main/java/org/thingsboard/server/service/report/LocalReportDataService.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.report; +import com.google.common.util.concurrent.ListenableFuture; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.springframework.stereotype.Service; @@ -32,6 +33,7 @@ import org.thingsboard.server.dao.alarm.AlarmService; import org.thingsboard.server.dao.report.ReportService; import org.thingsboard.server.dao.report.ReportTemplateService; import org.thingsboard.server.dao.resource.ImageService; +import org.thingsboard.server.exception.AccessDeniedException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.report.context.TbReportCtx; import org.thingsboard.server.report.datasource.ReportDataService; @@ -41,7 +43,9 @@ import org.thingsboard.server.service.security.permission.AccessControlService; import org.thingsboard.server.service.telemetry.TbTelemetryService; import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.concurrent.ExecutionException; import static org.thingsboard.server.common.data.report.configuration.timewindow.TimeIntervalCalculator.getIntervalTs; import static org.thingsboard.server.common.data.report.configuration.timewindow.TimeIntervalCalculator.getIntervalType; @@ -112,13 +116,13 @@ public class LocalReportDataService implements ReportDataService { @Override public List getTimeseries(EntityId entityId, List keys, Long startTs, Long endTs, Interval interval, String timeZone, Aggregation agg, SortOrder.Direction sortOrder, Integer limit, boolean useStrictDataTypes, TbReportCtx ctx) { - return tbTelemetryService.getTimeseries(entityId, keys, startTs, endTs, getIntervalType(interval), getIntervalTs(interval), timeZone, limit, agg, sortOrder.name(), useStrictDataTypes, getSecurityUser(ctx)).get(); // .get() will be interrupted on task processing timeout + return getOrEmptyIfAccessDenied(tbTelemetryService.getTimeseries(entityId, keys, startTs, endTs, getIntervalType(interval), getIntervalTs(interval), timeZone, limit, agg, sortOrder.name(), useStrictDataTypes, getSecurityUser(ctx))); // .get() will be interrupted on task processing timeout } @SneakyThrows @Override public List findTimeseriesByQueries(EntityId entityId, List queries, TbReportCtx ctx) { - return tbTelemetryService.getTimeseriesByReadQueries(entityId, queries, getSecurityUser(ctx)).get(); + return getOrEmptyIfAccessDenied(tbTelemetryService.getTimeseriesByReadQueries(entityId, queries, getSecurityUser(ctx))); } @Override @@ -127,6 +131,17 @@ public class LocalReportDataService implements ReportDataService { return reportService.createReport(report, data); } + private List getOrEmptyIfAccessDenied(ListenableFuture> future) throws InterruptedException, ExecutionException { + try { + return future.get(); + } catch (ExecutionException e) { + if (e.getCause() instanceof AccessDeniedException) { + return Collections.emptyList(); + } + throw e; + } + } + private SecurityUser getSecurityUser(TbReportCtx ctx) { return ((LocalTbReportCtxProvider.LocalTbReportCtx) ctx).getSecurityUser(); } diff --git a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java index 8a7129668a..90a6cb049e 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java +++ b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java @@ -358,6 +358,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.DEVICE_PROFILE, operation, entityId, deviceProfile); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(deviceProfile)); } @@ -376,6 +377,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.ASSET_PROFILE, operation, entityId, assetProfile); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(assetProfile)); } @@ -388,6 +390,7 @@ public class AccessValidator { } else { if (!operation.equals(Operation.READ_TELEMETRY)) { callback.onSuccess(ValidationResult.accessDenied("Allowed only READ_TELEMETRY operation!")); + return; } ApiUsageState apiUsageState = apiUsageStateService.findApiUsageStateById(currentUser.getTenantId(), new ApiUsageStateId(entityId.getId())); if (apiUsageState == null) { @@ -397,6 +400,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.API_USAGE_STATE, operation, entityId, apiUsageState); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(apiUsageState)); } @@ -415,6 +419,7 @@ public class AccessValidator { accessControlService.checkPermission(currentUser, Resource.OTA_PACKAGE, operation, entityId, otaPackage); } catch (ThingsboardException e) { callback.onSuccess(ValidationResult.accessDenied(e.getMessage())); + return; } callback.onSuccess(ValidationResult.ok(otaPackage)); } diff --git a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java index 50b2cd3b7b..bafaee6a3f 100644 --- a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java +++ b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java @@ -23,8 +23,8 @@ import org.thingsboard.server.dao.widget.WidgetsBundleService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.install.DatabaseSchemaSettingsService; import org.thingsboard.server.service.install.InstallScripts; -import org.thingsboard.server.service.install.lts.LtsMigrationService; -import org.thingsboard.server.service.install.lts.LtsVersion; +import org.thingsboard.server.service.install.lts.MigrationService; +import org.thingsboard.server.service.install.lts.Version; import org.thingsboard.server.service.install.update.DefaultDataUpdateService; import java.io.IOException; @@ -64,7 +64,7 @@ public class SystemPatchApplier { private final WidgetTypeService widgetTypeService; private final WidgetsBundleService widgetsBundleService; private final ImageService imageService; - private final LtsMigrationService ltsMigrationService; + private final MigrationService migrationService; @PostConstruct private void init() { @@ -100,7 +100,7 @@ public class SystemPatchApplier { // skipVersionCheck got us here with the database possibly already at the package version, where the // default half-open selection would be empty: pass it on so that run still applies the stored version's // own migration. - List appliedVersions = ltsMigrationService.applyMigrations(dbVersion, packageVersion, skipVersionCheck, () -> { + List appliedVersions = migrationService.applyMigrations(dbVersion, packageVersion, skipVersionCheck, () -> { // Between the schema and backfill phases: the schema phase may have added columns these definitions // reference, and the refreshed definitions are then in effect for the whole backfill run. Each file // is one jdbcTemplate.execute, so PostgreSQL runs it in a single implicit transaction and other @@ -124,7 +124,7 @@ public class SystemPatchApplier { int createdImages = createMissingSystemImages(); log.info("Created {} new system images", createdImages); - ltsMigrationService.recordVersions(appliedVersions); + migrationService.recordVersions(appliedVersions); schemaSettingsService.updateSchemaVersion(); log.info("System data patch update completed successfully"); @@ -139,11 +139,11 @@ public class SystemPatchApplier { log.trace("Package version: {}, DB schema version: {}", packageVersion, dbVersion); - LtsVersion packageVersionInfo; - LtsVersion dbVersionInfo; + Version packageVersionInfo; + Version dbVersionInfo; try { - packageVersionInfo = LtsVersion.parse(packageVersion); - dbVersionInfo = LtsVersion.parse(dbVersion); + packageVersionInfo = Version.parse(packageVersion); + dbVersionInfo = Version.parse(dbVersion); } catch (IllegalArgumentException e) { log.warn("Unable to parse versions. Package: {}, DB: {}", packageVersion, dbVersion); return false; diff --git a/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java b/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java index e60c9ae60d..b7cb597f12 100644 --- a/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java +++ b/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java @@ -22,7 +22,9 @@ import org.thingsboard.server.common.data.kv.TsKvEntry; import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.dao.timeseries.TimeseriesService; import org.thingsboard.server.service.security.AccessValidator; +import org.thingsboard.server.service.security.ValidationCallback; import org.thingsboard.server.service.security.ValidationResult; +import org.thingsboard.server.service.security.ValidationResultCode; import org.thingsboard.server.service.security.model.SecurityUser; import java.util.ArrayList; @@ -45,6 +47,10 @@ public class DefaultTbTelemetryService implements TbTelemetryService { accessValidator.validate(currentUser, Operation.READ_TELEMETRY, entityId, new FutureCallback<>() { @Override public void onSuccess(ValidationResult validationResult) { + if (validationResult.getResultCode() != ValidationResultCode.OK) { + onFailure(ValidationCallback.getException(validationResult)); + return; + } try { AggregationParams params; if (Aggregation.NONE.equals(agg)) { @@ -85,6 +91,10 @@ public class DefaultTbTelemetryService implements TbTelemetryService { accessValidator.validate(currentUser, Operation.READ_TELEMETRY, entityId, new FutureCallback<>() { @Override public void onSuccess(ValidationResult validationResult) { + if (validationResult.getResultCode() != ValidationResultCode.OK) { + onFailure(ValidationCallback.getException(validationResult)); + return; + } try { Futures.addCallback(tsService.findAllByQueries(currentUser.getTenantId(), entityId, new ArrayList<>(queries)), new FutureCallback<>() { @Override diff --git a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java index c03f6a059c..5d6df8ec02 100644 --- a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java +++ b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java @@ -991,72 +991,36 @@ public class DefaultWebSocketService implements WebSocketService { }, executor); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List keys, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - List>> futures = new ArrayList<>(); - for (AttributeScope scope : AttributeScope.values()) { - futures.add(attributesService.find(tenantId, entityId, scope, keys)); - } - - ListenableFuture> future = mergeAllAttributesFutures(futures); - Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List keys, final FutureCallback> callback) { + return on(r -> { + List>> futures = new ArrayList<>(); + for (AttributeScope scope : AttributeScope.values()) { + futures.add(attributesService.find(tenantId, entityId, scope, keys)); } - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + ListenableFuture> future = mergeAllAttributesFutures(futures); + Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + }, callback::onFailure); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List keys, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor()); - } - - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List keys, final FutureCallback> callback) { + return on(r -> Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor()), callback::onFailure); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - List>> futures = new ArrayList<>(); - for (AttributeScope scope : AttributeScope.values()) { - futures.add(attributesService.findAll(tenantId, entityId, scope)); - } - - ListenableFuture> future = mergeAllAttributesFutures(futures); - Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback> callback) { + return on(r -> { + List>> futures = new ArrayList<>(); + for (AttributeScope scope : AttributeScope.values()) { + futures.add(attributesService.findAll(tenantId, entityId, scope)); } - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + ListenableFuture> future = mergeAllAttributesFutures(futures); + Futures.addCallback(future, callback, MoreExecutors.directExecutor()); + }, callback::onFailure); } - private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback> callback) { - return new FutureCallback() { - @Override - public void onSuccess(@Nullable ValidationResult result) { - Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()); - } - - @Override - public void onFailure(Throwable t) { - callback.onFailure(t); - } - }; + private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback> callback) { + return on(r -> Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()), callback::onFailure); } private FutureCallback on(Consumer success, Consumer failure) { diff --git a/application/src/test/java/org/thingsboard/server/client/TbResourceApiClientTest.java b/application/src/test/java/org/thingsboard/server/client/TbResourceApiClientTest.java index 17bcbfe048..4434c753da 100644 --- a/application/src/test/java/org/thingsboard/server/client/TbResourceApiClientTest.java +++ b/application/src/test/java/org/thingsboard/server/client/TbResourceApiClientTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.client; import org.junit.Test; @@ -21,6 +22,7 @@ import java.io.File; import java.util.ArrayList; import java.util.Base64; import java.util.List; +import java.util.Set; import java.util.UUID; import static org.junit.Assert.assertEquals; @@ -79,7 +81,7 @@ public class TbResourceApiClientTest extends AbstractApiClientTest { PageDataTbResourceInfo jsResources = client.getResources(GetResourcesArgs.builder() .pageSize(100) .page(0) - .resourceType(ResourceType.JS_MODULE.getValue()) + .resourceType(Set.of(ResourceType.JS_MODULE)) .textSearch(TEST_PREFIX + "Resource_" + timestamp) .build()); assertEquals(5, jsResources.getData().size()); diff --git a/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java index 13f285e825..6ebd6ba29c 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.controller; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -10,8 +11,11 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.SaveDeviceWithCredentialsRequest; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery; import org.thingsboard.server.common.data.kv.BasicTsKvEntry; import org.thingsboard.server.common.data.kv.LongDataEntry; import org.thingsboard.server.common.data.query.AliasEntityId; @@ -22,9 +26,11 @@ import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.List; +import java.util.UUID; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.thingsboard.server.common.data.query.EntityKeyType.TIME_SERIES; @@ -291,6 +297,40 @@ public class TelemetryControllerTest extends AbstractControllerTest { Assert.assertTrue(tsDataAfterDeletion.get("key3").get(0).get("value").isNull()); } + @Test + public void testCustomerUserCannotReadTimeseriesOfNotAssignedDevice() throws Exception { + loginTenantAdmin(); + Device device = createDevice(); + tsService.save(tenantId, device.getId(), new BasicTsKvEntry(1000L, new LongDataEntry("t", 1L))).get(); + + loginCustomerAdminUser(); + String url = "/api/plugins/telemetry/DEVICE/{entityId}/values/timeseries?keys=t&startTs=0&endTs={endTs}"; + doGetAsync(url, device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden()); + doGetAsync(url + "&agg=SUM&interval=86400000", device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden()); + doGetAsync(url, UUID.randomUUID(), System.currentTimeMillis()).andExpect(status().isNotFound()); + List queries = List.of(new BaseReadTsKvQuery("t", 0, System.currentTimeMillis(), 10, "DESC")); + doPostAsync("/api/plugins/telemetry/DEVICE/" + device.getId() + "/values/timeseries", queries, String.class, status().isForbidden()); + + loginTenantAdmin(); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/DEVICE/" + device.getId().getId()).andExpect(status().isOk()); + + loginCustomerAdminUser(); + ObjectNode result = doGetAsync(url, ObjectNode.class, device.getUuidId(), System.currentTimeMillis()); + Assert.assertEquals(1L, result.get("t").get(0).get("value").asLong()); + } + + @Test + public void testCustomerUserCannotSaveDeviceProfileAttributes() throws Exception { + loginTenantAdmin(); + DeviceProfileId deviceProfileId = createDevice().getDeviceProfileId(); + + loginCustomerUser(); + doPostAsync("/api/plugins/telemetry/DEVICE_PROFILE/" + deviceProfileId + "/SERVER_SCOPE", "{\"attr\": \"value\"}", String.class, status().isForbidden()); + + await().during(1, TimeUnit.SECONDS).atMost(2, TimeUnit.SECONDS) + .until(() -> attributesService.find(tenantId, deviceProfileId, AttributeScope.SERVER_SCOPE, "attr").get().isEmpty()); + } + private Device createDevice() throws Exception { String testToken = "TEST_TOKEN"; diff --git a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java index b30023c0bc..f2b5ba2f45 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java @@ -15,6 +15,8 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.web.util.UriComponentsBuilder; import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionStatus; @@ -27,6 +29,8 @@ import org.thingsboard.server.common.data.notification.targets.platform.TenantAd import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.SortOrder; import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.common.data.query.EntityData; +import org.thingsboard.server.common.data.query.EntityTypeFilter; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.model.JwtPair; import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; @@ -43,6 +47,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; import org.thingsboard.server.service.security.auth.rest.LoginRequest; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.EntityDataUpdate; import java.time.Duration; import java.util.Arrays; @@ -144,6 +149,43 @@ public class TwoFactorAuthTest extends AbstractControllerTest { assertThat(currentUser.getId()).isEqualTo(user.getId()); } + @Test + public void testWsAuthCmd_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN); + + wsClient = buildAndConnectWebSocketClient(); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + } + + @Test + public void testWsQueryToken_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN); + + wsClient = buildAndConnectWebSocketClient("/api/ws?token=" + token); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + } + + @Test + public void testWs_accessTokenAcceptedAfterTwoFa() throws Exception { + TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa(); + logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN); + JsonNode tokenPair = readResponse(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + getCorrectTotp(totpTwoFaAccountConfig)) + .andExpect(status().isOk()), JsonNode.class); + validateAndSetJwtToken(tokenPair, username); + Device device = createDevice("2FA device", "2FA device token"); + + EntityTypeFilter deviceFilter = new EntityTypeFilter(); + deviceFilter.setEntityType(EntityType.DEVICE); + EntityDataUpdate update = getWsClient().sendEntityDataQuery(deviceFilter); + + assertThat(update.getData().getData()).singleElement() + .extracting(EntityData::getEntityId).isEqualTo(device.getId()); + } + @Test public void testTwoFaPreVerificationTokenLifetime() throws Exception { configureTotpTwoFa(twoFaSettings -> { diff --git a/application/src/test/java/org/thingsboard/server/controller/WebSocketApiTest.java b/application/src/test/java/org/thingsboard/server/controller/WebSocketApiTest.java index 7cd92647c1..8c10290d8b 100644 --- a/application/src/test/java/org/thingsboard/server/controller/WebSocketApiTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/WebSocketApiTest.java @@ -988,6 +988,18 @@ public class WebSocketApiTest extends AbstractControllerTest { assertThat(update.get("data").get("attr").get(0).get(1).asText()).isEqualTo(expectedAttrValue); } + @Test + public void testAttributesSubscription_customerUserNotAssignedDevice() throws Exception { + sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, List.of( + new BaseAttributeKvEntry(System.currentTimeMillis(), new StringDataEntry("attr", "secret")) + )); + + loginCustomerUser(); + JsonNode update = getWsClient().subscribeForAttributes(device.getId(), TbAttributeSubscriptionScope.SERVER_SCOPE.name(), List.of("attr")); + assertThat(update.get("errorCode").asInt()).isNotEqualTo(SubscriptionErrorCode.NO_ERROR.getCode()); + assertThat(update.path("data").isEmpty()).isTrue(); + } + @Test public void testEntityCountCmd_filterTypeSingularCompatibilityTest() throws Exception { ObjectNode oldFormatDeviceTypeFilterSingular = JacksonUtil.newObjectNode(); diff --git a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java index 8591952462..d45fdf064d 100644 --- a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java @@ -134,7 +134,7 @@ class ThingsboardInstallServiceTest { installService.performInstall(); - // The LTS files the chain applies reference PE-only tables and each of them runs as a single transaction, + // The migration files the chain applies reference PE-only tables and each of them runs as a single transaction, // so a converted CE database must be given those tables before the chain runs rather than after it. InOrder inOrder = inOrder(entityDatabaseSchemaService, databaseEntitiesUpgradeService, dataUpdateService); inOrder.verify(entityDatabaseSchemaService).createDatabaseSchema(false); diff --git a/application/src/test/java/org/thingsboard/server/service/housekeeper/HousekeeperServiceTest.java b/application/src/test/java/org/thingsboard/server/service/housekeeper/HousekeeperServiceTest.java index 16150e7b38..510a50a36c 100644 --- a/application/src/test/java/org/thingsboard/server/service/housekeeper/HousekeeperServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/housekeeper/HousekeeperServiceTest.java @@ -32,7 +32,9 @@ import org.thingsboard.server.common.data.EventInfo; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmComment; +import org.thingsboard.server.common.data.alarm.AlarmCommentInfo; import org.thingsboard.server.common.data.alarm.AlarmCommentSubType; +import org.thingsboard.server.common.data.alarm.AlarmCommentType; import org.thingsboard.server.common.data.alarm.AlarmRef; import org.thingsboard.server.common.data.alarm.AlarmSeverity; import org.thingsboard.server.common.data.alarm.EntityAlarm; @@ -323,6 +325,37 @@ public class HousekeeperServiceTest extends AbstractControllerTest { }); } + @Test + public void whenAlarmCommentIsDeleted_thenKeepOtherAlarmComments() throws Exception { + Device device = createDevice("test", "test"); + Alarm alarm = doPost("/api/alarm", Alarm.builder() + .tenantId(tenantId) + .originator(device.getId()) + .severity(AlarmSeverity.CRITICAL) + .type("test alarm with deleted comment") + .build(), Alarm.class); + AlarmId alarmId = alarm.getId(); + List comments = new ArrayList<>(); + for (int i = 1; i <= 3; i++) { + comments.add(doPost("/api/alarm/" + alarmId + "/comment", AlarmComment.builder() + .comment(JacksonUtil.newObjectNode().set("text", new TextNode("comment " + i))) + .build(), AlarmComment.class)); + } + assertThat(alarmCommentService.findAlarmComments(tenantId, alarmId, new PageLink(100)).getData()).hasSize(3); + + doDelete("/api/alarm/" + alarmId + "/comment/" + comments.get(0).getId()).andExpect(status().isOk()); + + TimeUnit.SECONDS.sleep(2); + List remaining = alarmCommentService.findAlarmComments(tenantId, alarmId, new PageLink(100)).getData(); + assertThat(remaining).hasSize(3); + assertThat(remaining).filteredOn(comment -> comment.getId().equals(comments.get(0).getId())) + .singleElement() + .satisfies(comment -> { + assertThat(comment.getType()).isEqualTo(AlarmCommentType.SYSTEM); + assertThat(comment.getComment().get("subtype").asText()).isEqualTo(AlarmCommentSubType.COMMENT_DELETED.name()); + }); + } + @Test public void whenDeviceIsDeleted_thenDeleteAllAlarms() throws Exception { Device device = createDevice("test", "test"); diff --git a/application/src/test/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsServiceTest.java index 2fc1d1a7fd..d412245ea4 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/DefaultDatabaseSchemaSettingsServiceTest.java @@ -23,8 +23,8 @@ import static org.mockito.Mockito.when; @MockitoSettings(strictness = Strictness.LENIENT) class DefaultDatabaseSchemaSettingsServiceTest { - private static final String PACKAGE_VERSION = "4.4.0"; - private static final long V_4_3_1_4 = 4_003_001_004L; + private static final String PACKAGE_VERSION = "4.4.1"; + private static final long V_4_3_1_6 = 4_003_001_006L; @Mock private ProjectInfo projectInfo; @@ -49,7 +49,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { @Test void aCeDatabaseAtTheSupportedVersionIsAcceptedAndTakesTheConversionBranch() { - givenSchemaSettings("CE", V_4_3_1_4); + givenSchemaSettings("CE", V_4_3_1_6); service.validateSchemaSettings(); @@ -58,7 +58,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { @Test void aPeDatabaseAtASupportedVersionIsAcceptedAndTakesThePlainUpgradeBranch() { - givenSchemaSettings("PE", V_4_3_1_4); + givenSchemaSettings("PE", V_4_3_1_6); service.validateSchemaSettings(); @@ -68,7 +68,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { @Test void aCeDatabaseOnALaterPatchOfTheSupportedLineIsAlsoAccepted() { // 4.3 keeps receiving patches, so the CE floor is a minimum rather than a single release. - givenSchemaSettings("CE", 4_003_001_005L); + givenSchemaSettings("CE", 4_003_001_007L); service.validateSchemaSettings(); @@ -77,7 +77,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { @Test void aCeDatabaseNewerThanThePePackageIsRejected() { - givenSchemaSettings("CE", 4_004_000_001L); + givenSchemaSettings("CE", 4_004_002_000L); assertThatThrownBy(() -> service.validateSchemaSettings()) .hasMessageContaining("newer than this ThingsBoard PE package"); @@ -85,22 +85,53 @@ class DefaultDatabaseSchemaSettingsServiceTest { @Test void aCeDatabaseBelowTheSupportedVersionIsRejectedAtTheWall() { - // 4.3.0.0: within the versions the PE branch accepts, but below the CE release that converts. - givenSchemaSettings("CE", 4_003_000_000L); + // 4.3.1.5: within the versions the PE branch accepts, but below the CE release that converts. + givenSchemaSettings("CE", 4_003_001_005L); assertThatThrownBy(() -> service.validateSchemaSettings()) .hasMessageContaining("transitioning from CE to PE") - .hasMessageContaining("4.3.1.4"); + .hasMessageContaining("4.3.1.6"); } @Test void aPeDatabaseAlreadyAtThePackageVersionIsRejected() { - givenSchemaSettings("PE", 4_004_000_000L); + givenSchemaSettings("PE", 4_004_001_000L); assertThatThrownBy(() -> service.validateSchemaSettings()) .hasMessageContaining("already upgraded to current version"); } + @Test + void aPeDatabaseAtTheFirstVersionOfTheSupportedFamilyIsAccepted() { + givenSchemaSettings("PE", 4_003_000_000L); + + service.validateSchemaSettings(); + } + + @Test + void aPeDatabaseOnAFutureMaintenanceVersionOfTheSupportedFamilyIsAccepted() { + givenSchemaSettings("PE", 4_003_002_000L); + + service.validateSchemaSettings(); + } + + @Test + void aPeDatabaseOnAnOlderVersionOfThePackageFamilyIsRejectedAsNotNeedingAnUpgrade() { + givenSchemaSettings("PE", 4_004_000_001L); + + assertThatThrownBy(() -> service.validateSchemaSettings()) + .hasMessageContaining("same LTS family") + .hasMessageContaining("applied automatically when ThingsBoard starts"); + } + + @Test + void aPeDatabaseOnANewerVersionOfThePackageFamilyIsRejected() { + givenSchemaSettings("PE", 4_004_002_000L); + + assertThatThrownBy(() -> service.validateSchemaSettings()) + .hasMessageContaining("is not supported for upgrade"); + } + @Test void aPeDatabaseAtAnUnsupportedVersionIsRejected() { givenSchemaSettings("PE", 4_002_002_000L); @@ -113,7 +144,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { void aDatabaseWithAnUnknownProductMarkerIsRejected() { // Neither CE nor PE: unchecked, the marker would silently select the PE branch and the CE-to-PE // conversion would be skipped on a database that needs it. - givenSchemaSettings("TB", V_4_3_1_4); + givenSchemaSettings("TB", V_4_3_1_6); assertThatThrownBy(() -> service.validateSchemaSettings()) .hasMessageContaining("unrecognized product"); @@ -121,7 +152,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { @Test void aDatabaseWithoutAProductMarkerIsRejected() { - givenSchemaSettings(null, V_4_3_1_4); + givenSchemaSettings(null, V_4_3_1_6); assertThatThrownBy(() -> service.validateSchemaSettings()) .hasMessageContaining("unrecognized product"); @@ -131,7 +162,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { void anUnrecognizedProductMarkerIsRejectedByTheBranchSelectorItself() { // The guard has to live where the branch is chosen: validateSchemaSettings() returns early when // SKIP_SCHEMA_VERSION_CHECK is set, and the upgrade then asks isUpgradeFromCe() regardless. - givenSchemaSettings("TB", V_4_3_1_4); + givenSchemaSettings("TB", V_4_3_1_6); assertThatThrownBy(() -> service.isUpgradeFromCe()) .hasMessageContaining("unrecognized product"); @@ -139,7 +170,7 @@ class DefaultDatabaseSchemaSettingsServiceTest { @Test void aMissingProductMarkerIsRejectedByTheBranchSelectorItself() { - givenSchemaSettings(null, V_4_3_1_4); + givenSchemaSettings(null, V_4_3_1_6); assertThatThrownBy(() -> service.isUpgradeFromCe()) .hasMessageContaining("unrecognized product"); diff --git a/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeAlarmShardingIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeAlarmShardingIntegrationTest.java index 3105391880..d13a14fb84 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeAlarmShardingIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeAlarmShardingIntegrationTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** - * CE-to-PE twin of the 4.3.1.4 alarm-sharding coverage in {@code LtsMigrationIntegrationTest}: the same schema + * CE-to-PE twin of the 4.3.1.4 alarm-sharding coverage in {@code MigrationIntegrationTest}: the same schema * change (alarm_comment FK drop, entity_alarm.originator_id ADD COLUMN) plus the deliberately single-statement * originator backfill live in upgrade/pe/schema_update.sql and are executed by no other test. The whole file is * idempotent by design (SqlDatabaseUpgradeService sends it as one execute), so the test runs it verbatim — twice, diff --git a/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeChainIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeChainIntegrationTest.java index 526c7cdccd..131cb96444 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeChainIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/PeUpgradeChainIntegrationTest.java @@ -35,7 +35,7 @@ import org.thingsboard.server.dao.tenant.TenantService; import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.dao.wl.WhiteLabelingService; import org.thingsboard.server.service.component.ComponentDiscoveryService; -import org.thingsboard.server.service.install.lts.LtsMigrationService; +import org.thingsboard.server.service.install.lts.MigrationService; import org.thingsboard.server.service.install.update.DefaultDataUpdateService; import java.util.ArrayList; @@ -55,7 +55,7 @@ import static org.mockito.Mockito.when; /** * Two parts of the offline upgrade driven against a real database: the CE-to-PE data conversion * ({@code updateData(true)}) replayed the way a crashed conversion replays it, and a PE database stamped at a - * pre-4.4 version taken to the package version by the real LTS chain ({@code upgradeDatabase(false)}), from the + * pre-4.4 version taken to the package version by the real migration chain ({@code upgradeDatabase(false)}), from the * position the chain now runs from for both sources. *

    * What is not here is the CE schema fork, {@code upgradeDatabase(true)}. The fixture below builds CE-shaped @@ -81,7 +81,7 @@ public class PeUpgradeChainIntegrationTest extends AbstractControllerTest { private static final List COUNTED_TABLES = List.of( "entity_group", "relation", "tenant", "customer", "tb_user", "device", "asset", "dashboard"); - // Columns added by the LTS files the chain selects. report is the PE-only table the whole ordering fix exists + // Columns added by the migration files the chain selects. report is the PE-only table the whole ordering fix exists // for, so its two 4.4 columns are in the set even though report_info_view's SELECT r.* captures them. private static final List V_4_3_1_2_COLUMNS = List.of( new Column("calculated_field", "additional_info", "varchar"), @@ -104,7 +104,7 @@ public class PeUpgradeChainIntegrationTest extends AbstractControllerTest { @Autowired private InstallScripts installScripts; @Autowired - private LtsMigrationService ltsMigrationService; + private MigrationService migrationService; @Autowired private PlatformTransactionManager transactionManager; @@ -281,8 +281,8 @@ public class PeUpgradeChainIntegrationTest extends AbstractControllerTest { /** * The real conversion, wired to the real DAO services. Only the collaborators outside it are stood in for: - * the two install-profile beans a test context does not have, and the LTS data phase, which - * {@link org.thingsboard.server.service.install.lts.LtsMigrationIntegrationTest} owns. + * the two install-profile beans a test context does not have, and the migration data phase, which + * {@link org.thingsboard.server.service.install.lts.MigrationIntegrationTest} owns. */ private DefaultDataUpdateService ceDataUpdateService() { return new DefaultDataUpdateService(tenantService, relationService, ruleChainService, integrationService, @@ -290,7 +290,7 @@ public class PeUpgradeChainIntegrationTest extends AbstractControllerTest { dashboardService, entityViewService, edgeService, agentProfileService, mock(SystemDataLoaderService.class), mock(ComponentDiscoveryService.class), inlineUpgradeExecutor(), schemaSettingsStubbedAt("4.3.1.4"), - mock(LtsMigrationService.class)); + mock(MigrationService.class)); } /** @@ -310,7 +310,7 @@ public class PeUpgradeChainIntegrationTest extends AbstractControllerTest { /** The real schema upgrade, with only the version pair it is driven over stubbed. */ private SqlDatabaseUpgradeService upgradeService(String fromVersion) { return new SqlDatabaseUpgradeService(installScripts, jdbcTemplate, transactionManager, - schemaSettingsStubbedAt(fromVersion), ltsMigrationService); + schemaSettingsStubbedAt(fromVersion), migrationService); } private DatabaseSchemaSettingsService schemaSettingsStubbedAt(String dbVersion) { diff --git a/application/src/test/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeServiceTest.java index 98e9ff24f9..4b79aa5c18 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/SqlDatabaseUpgradeServiceTest.java @@ -12,7 +12,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.StatementCallback; import org.springframework.transaction.PlatformTransactionManager; -import org.thingsboard.server.service.install.lts.LtsMigrationService; +import org.thingsboard.server.service.install.lts.MigrationService; import java.io.IOException; import java.nio.file.Files; @@ -27,14 +27,13 @@ import static org.mockito.Mockito.when; /** * A converted CE database is at a CE version, not at the package version, so the CE-to-PE delta cannot be the whole - * schema upgrade: the delta gives the database the PE shape of the version it is already at, and the LTS chain then + * schema upgrade: the delta gives the database the PE shape of the version it is already at, and the migration chain then * has to take it the rest of the way exactly as it does for a PE source. */ @ExtendWith(MockitoExtension.class) class SqlDatabaseUpgradeServiceTest { private static final String PE_DELTA_SQL = "-- the CE to PE delta\n"; - private static final String BASIC_SQL = "-- the basic schema update\n"; private static final String DB_VERSION = "4.3.1.4"; private static final String PACKAGE_VERSION = "4.4.0.0"; @@ -47,7 +46,7 @@ class SqlDatabaseUpgradeServiceTest { @Mock private DatabaseSchemaSettingsService schemaSettingsService; @Mock - private LtsMigrationService ltsMigrationService; + private MigrationService migrationService; @Mock private Statement statement; @@ -60,24 +59,22 @@ class SqlDatabaseUpgradeServiceTest { @SuppressWarnings("unchecked") void setUp() throws IOException { writeSchemaUpdate("pe", PE_DELTA_SQL); - writeSchemaUpdate("basic", BASIC_SQL); when(installScripts.getDataDir()).thenReturn(dataDir.toString()); when(schemaSettingsService.getDbSchemaVersion()).thenReturn(DB_VERSION); when(schemaSettingsService.getPackageSchemaVersion()).thenReturn(PACKAGE_VERSION); // Run the callback the service passes, so the SQL it hands to the statement can be asserted on. when(jdbcTemplate.execute(any(StatementCallback.class))) .thenAnswer(invocation -> ((StatementCallback) invocation.getArgument(0)).doInStatement(statement)); - service = new SqlDatabaseUpgradeService(installScripts, jdbcTemplate, transactionManager, schemaSettingsService, ltsMigrationService); + service = new SqlDatabaseUpgradeService(installScripts, jdbcTemplate, transactionManager, schemaSettingsService, migrationService); } @Test void ceToPeUpgradeAppliesTheDeltaAndThenTheRestOfTheChain() throws Exception { service.upgradeDatabase(true); - InOrder inOrder = inOrder(statement, ltsMigrationService); + InOrder inOrder = inOrder(statement, migrationService); inOrder.verify(statement).execute(PE_DELTA_SQL); - inOrder.verify(statement).execute(BASIC_SQL); - inOrder.verify(ltsMigrationService).runSchemaMigrations(DB_VERSION, PACKAGE_VERSION, false); + inOrder.verify(migrationService).runSchemaMigrations(DB_VERSION, PACKAGE_VERSION, false); } @Test @@ -85,20 +82,18 @@ class SqlDatabaseUpgradeServiceTest { service.upgradeDatabase(false); verify(statement, never()).execute(PE_DELTA_SQL); - InOrder inOrder = inOrder(statement, ltsMigrationService); - inOrder.verify(statement).execute(BASIC_SQL); - inOrder.verify(ltsMigrationService).runSchemaMigrations(DB_VERSION, PACKAGE_VERSION, false); + verify(migrationService).runSchemaMigrations(DB_VERSION, PACKAGE_VERSION, false); } @Test - void aForcedReUpgradeIsCarriedIntoTheLtsMigrations() throws Exception { + void aForcedReUpgradeIsCarriedIntoTheMigrations() throws Exception { // The only test that can tell the flag apart from a hard-coded false: everywhere else it is Mockito's // default that the assertion reads back. when(schemaSettingsService.isForcedReUpgrade()).thenReturn(true); service.upgradeDatabase(false); - verify(ltsMigrationService).runSchemaMigrations(DB_VERSION, PACKAGE_VERSION, true); + verify(migrationService).runSchemaMigrations(DB_VERSION, PACKAGE_VERSION, true); } private void writeSchemaUpdate(String directory, String sql) throws IOException { diff --git a/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java index f8f1cd800d..74b22e8ec5 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java @@ -130,7 +130,7 @@ class SqlEntityDatabaseSchemaServiceClusterIdTest extends AbstractPostgresContai .hasCauseInstanceOf(SQLException.class); } - /** The production DDL, not retyped: LtsMigrationIntegrationTest pins these constants against schema-entities.sql. */ + /** The production DDL, not retyped: MigrationIntegrationTest pins these constants against schema-entities.sql. */ private static List productionClusterDdl() { return List.of(TbClusterSchema.CREATE_CLUSTER_TABLE_QUERY, TbClusterSchema.CREATE_CLUSTER_SINGLE_ROW_INDEX_QUERY); } diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java similarity index 95% rename from application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java index 8d2fdd61cc..4d0e570e04 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java @@ -48,7 +48,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @DaoSqlTest -public class LtsMigrationIntegrationTest extends AbstractControllerTest { +public class MigrationIntegrationTest extends AbstractControllerTest { private static final long V_4_2_2_2 = 4_002_002_002L; private static final long V_4_2_2_3 = 4_002_002_003L; @@ -62,7 +62,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5"); @Autowired - private LtsMigrationService ltsMigrationService; + private MigrationService migrationService; @Autowired private WidgetsBundleService widgetsBundleService; @Autowired @@ -72,7 +72,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { @Autowired private InstallScripts installScripts; @Autowired - private List migrations; + private List migrations; @Autowired private V4_3_1_4Migration v4314Migration; @@ -135,7 +135,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { // applyMigrations returns the applied versions; recordVersions stamps them (see SystemPatchApplier for // where that call sits relative to its own sync work). - ltsMigrationService.recordVersions(ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", false, () -> {})); + migrationService.recordVersions(migrationService.applyMigrations("4.2.2.2", "4.2.2.3", false, () -> {})); // 1. The version's SQL ran: iot_hub_installed_item table now exists. assertTrue(tableExists("iot_hub_installed_item")); @@ -152,9 +152,9 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { @Test public void reRunFromCurrentVersionIsNoOp() { - ltsMigrationService.recordVersions(ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", false, () -> {})); + migrationService.recordVersions(migrationService.applyMigrations("4.2.2.2", "4.2.2.3", false, () -> {})); // Re-running from the now-current version selects an empty range — nothing changes, nothing throws. - ltsMigrationService.applyMigrations("4.2.2.3", "4.2.2.3", false, () -> {}); + migrationService.applyMigrations("4.2.2.3", "4.2.2.3", false, () -> {}); assertEquals(Long.valueOf(V_4_2_2_3), jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); @@ -169,7 +169,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { jdbcTemplate.execute("DROP TABLE IF EXISTS iot_hub_installed_item"); // Drive the offline major-upgrade path over the real supported range against the real DB. - ltsMigrationService.runSchemaMigrations("4.2.2.2", "4.2.2.3", false); + migrationService.runSchemaMigrations("4.2.2.2", "4.2.2.3", false); // (a) the schema effects landed: the table the 4.2.2.3 SQL creates now exists. assertTrue(tableExists("iot_hub_installed_item")); // (c) the offline schema phase records NO schema version -- the offline flow tracks the package version @@ -177,7 +177,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { assertEquals(Long.valueOf(V_4_2_2_2), jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); - ltsMigrationService.runDataMigrations("4.2.2.2", "4.2.2.3", false); + migrationService.runDataMigrations("4.2.2.2", "4.2.2.3", false); // (b) the data apply() ran: the obsolete bundle was deleted and its type marked deprecated. assertNull(widgetsBundleService.findWidgetsBundleByTenantIdAndAlias(TenantId.SYS_TENANT_ID, OBSOLETE_ALIAS)); WidgetTypeDetails type = widgetTypeService.findWidgetTypeDetailsById(TenantId.SYS_TENANT_ID, widgetTypeId); @@ -212,7 +212,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { try { // Drive the runner over a range whose target (4.3.1.2) selects only the 4.3.1.2 migration. - ltsMigrationService.applyMigrations("4.3.1.1", "4.3.1.2", false, () -> {}); + migrationService.applyMigrations("4.3.1.1", "4.3.1.2", false, () -> {}); // The 4.3.1.2 schema SQL ran: every PE-specific column and the unique constraint exist again. assertTrue(columnExists("api_usage_state", "ai")); @@ -256,7 +256,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { try { // Drive the runner over a range whose target (4.3.1.4) selects only the 4.3.1.4 migration. - ltsMigrationService.recordVersions(ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.4", false, () -> {})); + migrationService.recordVersions(migrationService.applyMigrations("4.3.1.3", "4.3.1.4", false, () -> {})); // The schema_update.sql ran: the alarm_comment -> alarm cascade FK is gone and the column is back. assertFalse(constraintExists("fk_alarm_comment_alarm_id")); @@ -327,7 +327,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { v4314Migration.batchSize = 3; try { // Drive the runner over a range whose target (4.3.1.4) selects only the 4.3.1.4 migration. - ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.4", false, () -> {}); + migrationService.applyMigrations("4.3.1.3", "4.3.1.4", false, () -> {}); // Every seeded row got ITS OWN alarm's originator, across all three windows and both boundaries. for (int i = 0; i < rowAlarms.size(); i++) { @@ -369,7 +369,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { jdbcTemplate.execute("DROP TABLE IF EXISTS tb_cluster"); assertFalse(tableExists("tb_cluster")); - ltsMigrationService.applyMigrations("4.3.1.5", "4.3.1.6", false, () -> {}); + migrationService.applyMigrations("4.3.1.5", "4.3.1.6", false, () -> {}); assertTrue(tableExists("tb_cluster")); assertEquals(Long.valueOf(1L), jdbcTemplate.queryForObject("SELECT COUNT(*) FROM tb_cluster", Long.class)); @@ -384,10 +384,10 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { try { UUID existing = UUID.randomUUID(); jdbcTemplate.execute("DROP TABLE IF EXISTS tb_cluster"); - ltsMigrationService.applyMigrations("4.3.1.5", "4.3.1.6", false, () -> {}); + migrationService.applyMigrations("4.3.1.5", "4.3.1.6", false, () -> {}); jdbcTemplate.update("UPDATE tb_cluster SET cluster_id = ?::uuid", existing.toString()); - ltsMigrationService.applyMigrations("4.3.1.5", "4.3.1.6", false, () -> {}); + migrationService.applyMigrations("4.3.1.5", "4.3.1.6", false, () -> {}); assertEquals(List.of(existing.toString()), jdbcTemplate.queryForList("SELECT cluster_id FROM tb_cluster", String.class)); @@ -472,7 +472,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { // The walk discovers by the same DDL forms the comparison parses, so a script whose tb_cluster block // was reformatted past those regexes would leave the compared set without a word - the one blind spot // a self-selecting scan has. These two always carry the shape, so they are the floor under it: - // upgrade/pe makes the table on a CE-to-PE conversion, the current LTS baseline on a fresh upgrade. + // upgrade/pe makes the table on a CE-to-PE conversion, the current baseline on a fresh upgrade. List required = List.of( upgradeDir().resolve(Paths.get("pe", SCHEMA_UPDATE_SQL)), upgradeDir().resolve(Paths.get("lts", "4.4.0.0", SCHEMA_UPDATE_SQL))); @@ -525,7 +525,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { /** * Every shipped script that carries a copy of the {@code tb_cluster} shape, found by walking the upgrade - * tree rather than from a list: the next LTS directory to touch the table would otherwise be checked by + * tree rather than from a list: the next migration directory to touch the table would otherwise be checked by * nothing while the test above read as proof of coverage. Discovery is by the DDL forms the comparison * itself parses, not by a mention of the table name - a script that only names it in a comment or deletes * from it says nothing about shape and would fail here for nothing. @@ -560,9 +560,9 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { assertFalse(tableExists("iot_hub_installed_item")); // Offline schema phase over the whole supported cross-family range. - ltsMigrationService.runSchemaMigrations("4.3.0.0", "4.4.0.0", false); + migrationService.runSchemaMigrations("4.3.0.0", "4.4.0.0", false); - // 4.4.0.0 baseline DDL landed (this is what used to live in basic/schema_update.sql)... + // 4.4.0.0 baseline DDL landed... assertTrue(columnExists("rule_chain", "notes")); // ...and the in-range older-family 4.3.1.x beans ran too. assertTrue(columnExists("calculated_field", "additional_info")); @@ -573,14 +573,14 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { public void migrationDirectoriesAndBeansStayInSyncBothWays() { Path ltsDir = Paths.get(installScripts.getDataDir(), "upgrade", "lts"); Set dirVersions = listDirVersions(ltsDir); - Set beanVersions = migrations.stream().map(LtsMigration::getVersion).collect(Collectors.toSet()); + Set beanVersions = migrations.stream().map(Migration::getVersion).collect(Collectors.toSet()); // Every on-disk migration directory must have a registered bean with the same version. // Otherwise select() (which iterates beans, not dirs) silently skips the SQL dir. Set dirsWithoutBean = dirVersions.stream() .filter(v -> !beanVersions.contains(v)) .collect(Collectors.toSet()); - assertTrue("Migration directories without a registered LtsMigration bean: " + dirsWithoutBean, + assertTrue("Migration directories without a registered Migration bean: " + dirsWithoutBean, dirsWithoutBean.isEmpty()); // Every registered bean must have a matching directory, unless it is explicitly allowed to be SQL-less. @@ -589,7 +589,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { .filter(v -> !dirVersions.contains(v)) .filter(v -> !SQL_LESS_ALLOWED.contains(v)) .collect(Collectors.toSet()); - assertTrue("Registered LtsMigration beans without a matching directory (and not SQL-less allowed): " + beansWithoutDir, + assertTrue("Registered Migration beans without a matching directory (and not SQL-less allowed): " + beansWithoutDir, beansWithoutDir.isEmpty()); } @@ -602,7 +602,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { .map(p -> p.getFileName().toString()) .collect(Collectors.toSet()); } catch (IOException e) { - throw new UncheckedIOException("Failed to list LTS migration directories: " + ltsDir, e); + throw new UncheckedIOException("Failed to list migration directories: " + ltsDir, e); } } @@ -686,7 +686,7 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { } private static String readResource(String name) { - try (InputStream in = LtsMigrationIntegrationTest.class.getClassLoader().getResourceAsStream(name)) { + try (InputStream in = MigrationIntegrationTest.class.getClassLoader().getResourceAsStream(name)) { assertNotNull(name + " on the test classpath", in); return new String(in.readAllBytes(), StandardCharsets.UTF_8); } catch (IOException e) { diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationServiceTest.java similarity index 85% rename from application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java rename to application/src/test/java/org/thingsboard/server/service/install/lts/MigrationServiceTest.java index f9fe083fe7..4245e47206 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationServiceTest.java @@ -28,7 +28,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -class LtsMigrationServiceTest { +class MigrationServiceTest { private JdbcTemplate jdbcTemplate; private InstallScripts installScripts; @@ -55,24 +55,24 @@ class LtsMigrationServiceTest { } /** Records which apply() hooks fired, in order. */ - private LtsMigration migration(String version, List applied) { - return new LtsMigration() { + private Migration migration(String version, List applied) { + return new Migration() { @Override public String getVersion() { return version; } @Override public void apply() { applied.add(version); } }; } /** Records apply() and applyAfterCommit() calls (distinctly tagged) into a single shared ordered list. */ - private LtsMigration migrationWithAfterCommit(String version, List sequence) { - return new LtsMigration() { + private Migration migrationWithAfterCommit(String version, List sequence) { + return new Migration() { @Override public String getVersion() { return version; } @Override public void apply() { sequence.add("apply(" + version + ")"); } @Override public void applyAfterCommit() { sequence.add("applyAfterCommit(" + version + ")"); } }; } - private LtsMigrationService service(List migrations) { - return new LtsMigrationService(jdbcTemplate, installScripts, schemaSettingsService, txManager, migrations); + private MigrationService service(List migrations) { + return new MigrationService(jdbcTemplate, installScripts, schemaSettingsService, txManager, migrations); } @Test @@ -81,7 +81,7 @@ class LtsMigrationServiceTest { writeSql("4.2.2.3", "SELECT 1;"); writeSql("4.2.2.4", "SELECT 2;"); // intentionally unsorted input; service must sort ascending - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.2.2.4", applied), migration("4.2.2.2", applied), migration("4.2.2.3", applied))); @@ -100,7 +100,7 @@ class LtsMigrationServiceTest { List applied = new ArrayList<>(); writeSql("4.2.2.3", "SELECT 1;"); writeSql("4.2.2.4", "SELECT 2;"); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.2.2.3", applied), migration("4.2.2.4", applied))); List appliedVersions = service.applyMigrations("4.2.2.2", "4.2.2.4", false, () -> {}); @@ -117,7 +117,7 @@ class LtsMigrationServiceTest { // A cross-family 4.3 -> 4.4 offline upgrade now runs the real in-range 4.3.1.x beans (the source has // not passed them) alongside the new 4.4 baseline bean -- each exactly once. No 4.4-family bean // reproduces the 4.3.1.x work anymore. - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.2.2.3", applied), migration("4.3.1.2", applied), migration("4.3.1.3", applied), @@ -132,7 +132,7 @@ class LtsMigrationServiceTest { @Test void applyMigrationsRunsAndReturnsEachInRangeVersionOnCrossFamilyUpgrade() { List applied = new ArrayList<>(); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.2.2.3", applied), migration("4.3.1.2", applied), migration("4.3.1.3", applied), @@ -152,7 +152,7 @@ class LtsMigrationServiceTest { writeSql("4.3.1.2", "SELECT 2;"); writeSql("4.3.1.3", "SELECT 3;"); writeSql("4.4.0.0", "SELECT 4;"); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.2.2.3", applied), migration("4.3.1.2", applied), migration("4.3.1.3", applied), @@ -169,46 +169,46 @@ class LtsMigrationServiceTest { @Test void isInRangePredicate() { - LtsVersion from = LtsVersion.parse("4.3.1.1"); - LtsVersion to = LtsVersion.parse("4.3.1.3"); + Version from = Version.parse("4.3.1.1"); + Version to = Version.parse("4.3.1.3"); // within-family in range - assertTrue(LtsVersion.parse("4.3.1.2").isInRange(from, to)); + assertTrue(Version.parse("4.3.1.2").isInRange(from, to)); // the target itself (upper boundary, inclusive) assertTrue(to.isInRange(from, to)); // at from (lower boundary, exclusive) assertFalse(from.isInRange(from, to)); // below from - assertFalse(LtsVersion.parse("4.3.1.0").isInRange(from, to)); + assertFalse(Version.parse("4.3.1.0").isInRange(from, to)); // above to - assertFalse(LtsVersion.parse("4.3.1.4").isInRange(from, to)); + assertFalse(Version.parse("4.3.1.4").isInRange(from, to)); // Cross-family: an in-range older-family bean IS now selected (the whole point of the loosened filter), // as is the target-family baseline; only a bean below `from` stays out of range. - LtsVersion crossFrom = LtsVersion.parse("4.3.0.0"); - LtsVersion crossTo = LtsVersion.parse("4.4.0.0"); - assertTrue(LtsVersion.parse("4.3.1.3").isInRange(crossFrom, crossTo)); + Version crossFrom = Version.parse("4.3.0.0"); + Version crossTo = Version.parse("4.4.0.0"); + assertTrue(Version.parse("4.3.1.3").isInRange(crossFrom, crossTo)); assertTrue(crossTo.isInRange(crossFrom, crossTo)); - assertFalse(LtsVersion.parse("4.2.2.3").isInRange(crossFrom, crossTo)); + assertFalse(Version.parse("4.2.2.3").isInRange(crossFrom, crossTo)); } @Test void reproductionDuplicateBeanSitsBelowSupportedSourceFloor() { - // Load-bearing invariant (see LtsMigrationService.select): the only reproduction-duplicate pair is + // Load-bearing invariant (see MigrationService.select): the only reproduction-duplicate pair is // 4.2.2.3 <-> 4.3.1.3 (both do the solution-template / widget-bundle work). For the loosened (from, to] // filter to never select both in a single supported upgrade, the duplicate 4.2.2.3 must sit strictly - // below the minimum supported upgrade source. That floor is 4.3.0.0 (SUPPORTED_VERSIONS_FOR_UPGRADE). - LtsVersion duplicate = LtsVersion.parse("4.2.2.3"); - LtsVersion supportedSourceFloor = LtsVersion.parse("4.3.0.0"); + // below the minimum supported upgrade source. That floor is 4.3.0.0 (SUPPORTED_FAMILIES_FOR_UPGRADE). + Version duplicate = Version.parse("4.2.2.3"); + Version supportedSourceFloor = Version.parse("4.3.0.0"); assertTrue(duplicate.compareTo(supportedSourceFloor) < 0); // So on any supported cross-family upgrade (from >= floor), the duplicate is out of range. - assertFalse(duplicate.isInRange(supportedSourceFloor, LtsVersion.parse("4.4.0.0"))); + assertFalse(duplicate.isInRange(supportedSourceFloor, Version.parse("4.4.0.0"))); } @Test void reRunAtCurrentVersionIsNoOp() throws Exception { List applied = new ArrayList<>(); writeSql("4.2.2.3", "SELECT 1;"); - LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + MigrationService service = service(List.of(migration("4.2.2.3", applied))); List appliedVersions = service.applyMigrations("4.2.2.3", "4.2.2.3", false, () -> {}); @@ -223,7 +223,7 @@ class LtsMigrationServiceTest { writeSql("4.3.1.3", "SELECT 1;"); writeSql("4.4.0.0", "SELECT 2;"); writeSql("4.4.0.1", "SELECT 3;"); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.3.1.3", applied), migration("4.4.0.0", applied), migration("4.4.0.1", applied))); // SKIP_SCHEMA_VERSION_CHECK on a database already at the package version: the point of the flag is that this @@ -238,7 +238,7 @@ class LtsMigrationServiceTest { @Test void forcedRunAtCurrentVersionReRunsThatVersionDataOnly() { List applied = new ArrayList<>(); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.3.1.3", applied), migration("4.4.0.0", applied), migration("4.4.0.1", applied))); service.runDataMigrations("4.4.0.0", "4.4.0.0", true); @@ -270,7 +270,7 @@ class LtsMigrationServiceTest { @Test void forcedApplyMigrationsAtCurrentVersionReRunsAndReturnsThatVersion() { List applied = new ArrayList<>(); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migration("4.3.1.3", applied), migration("4.4.0.0", applied), migration("4.4.0.1", applied))); // The no-downtime twin of the above: SKIP_PATCH_VERSION_CHECK got the patch past its version check with the @@ -301,14 +301,14 @@ class LtsMigrationServiceTest { @Test void isInClosedRangePredicate() { - LtsVersion from = LtsVersion.parse("4.3.1.1"); - LtsVersion to = LtsVersion.parse("4.3.1.3"); + Version from = Version.parse("4.3.1.1"); + Version to = Version.parse("4.3.1.3"); // both boundaries inclusive, unlike isInRange assertTrue(from.isInClosedRange(from, to)); assertTrue(to.isInClosedRange(from, to)); - assertTrue(LtsVersion.parse("4.3.1.2").isInClosedRange(from, to)); - assertFalse(LtsVersion.parse("4.3.1.0").isInClosedRange(from, to)); - assertFalse(LtsVersion.parse("4.3.1.4").isInClosedRange(from, to)); + assertTrue(Version.parse("4.3.1.2").isInClosedRange(from, to)); + assertFalse(Version.parse("4.3.1.0").isInClosedRange(from, to)); + assertFalse(Version.parse("4.3.1.4").isInClosedRange(from, to)); // a single-version range holds exactly that version assertTrue(to.isInClosedRange(to, to)); assertFalse(from.isInClosedRange(to, to)); @@ -318,7 +318,7 @@ class LtsMigrationServiceTest { void runSchemaMigrationsRunsSqlButNeverAppliesOrRecords() throws Exception { List applied = new ArrayList<>(); writeSql("4.2.2.3", "SELECT 1;"); - LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + MigrationService service = service(List.of(migration("4.2.2.3", applied))); service.runSchemaMigrations("4.2.2.2", "4.2.2.3", false); @@ -331,7 +331,7 @@ class LtsMigrationServiceTest { void runDataMigrationsAppliesButNeverRunsSqlOrRecords() throws Exception { List applied = new ArrayList<>(); writeSql("4.2.2.3", "SELECT 1;"); - LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + MigrationService service = service(List.of(migration("4.2.2.3", applied))); service.runDataMigrations("4.2.2.2", "4.2.2.3", false); @@ -344,7 +344,7 @@ class LtsMigrationServiceTest { void runDataMigrationsAppliesAndAppliesAfterCommitButNeverRunsSqlOrRecords() throws Exception { List sequence = new ArrayList<>(); writeSql("4.2.2.3", "SELECT 1;"); - LtsMigrationService service = service(List.of(migrationWithAfterCommit("4.2.2.3", sequence))); + MigrationService service = service(List.of(migrationWithAfterCommit("4.2.2.3", sequence))); service.runDataMigrations("4.2.2.2", "4.2.2.3", false); @@ -356,7 +356,7 @@ class LtsMigrationServiceTest { @Test void migrationWithoutSqlFileStillAppliesAndReturnsVersion() { List applied = new ArrayList<>(); - LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + MigrationService service = service(List.of(migration("4.2.2.3", applied))); List appliedVersions = service.applyMigrations("4.2.2.2", "4.2.2.3", false, () -> {}); @@ -368,7 +368,7 @@ class LtsMigrationServiceTest { @Test void applyMigrationsNeverCallsUpdateSchemaVersionItself() { List applied = new ArrayList<>(); - LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + MigrationService service = service(List.of(migration("4.2.2.3", applied))); service.applyMigrations("4.2.2.2", "4.2.2.3", false, () -> {}); @@ -381,7 +381,7 @@ class LtsMigrationServiceTest { List events = new ArrayList<>(); Mockito.doAnswer(invocation -> events.add("record:" + invocation.getArgument(0))) .when(schemaSettingsService).updateSchemaVersion(anyString()); - LtsMigrationService service = service(List.of()); + MigrationService service = service(List.of()); service.recordVersions(List.of("4.3.1.2", "4.3.1.3")); @@ -389,8 +389,8 @@ class LtsMigrationServiceTest { } // Records apply() and applyAfterCommit() into a shared, ordered event log so their sequence can be asserted. - private LtsMigration recordingMigration(String version, List events) { - return new LtsMigration() { + private Migration recordingMigration(String version, List events) { + return new Migration() { @Override public String getVersion() { return version; } @Override public void apply() { events.add("apply:" + version); } @Override public void applyAfterCommit() { events.add("afterCommit:" + version); } @@ -400,7 +400,7 @@ class LtsMigrationServiceTest { @Test void applyMigrationsRunsApplyThenAfterCommitAndReturnsTheAppliedVersion() { List events = new ArrayList<>(); - LtsMigrationService service = service(List.of(recordingMigration("4.3.1.3", events))); + MigrationService service = service(List.of(recordingMigration("4.3.1.3", events))); List appliedVersions = service.applyMigrations("4.3.1.2", "4.3.1.3", false, () -> {}); @@ -411,7 +411,7 @@ class LtsMigrationServiceTest { @Test void applyMigrationsPropagatesAnAfterCommitFailureAndStampsNoVersion() { - LtsMigrationService service = service(List.of(new LtsMigration() { + MigrationService service = service(List.of(new Migration() { @Override public String getVersion() { return "4.3.1.3"; } @Override public void applyAfterCommit() { throw new IllegalStateException("backfill failed"); } })); @@ -427,7 +427,7 @@ class LtsMigrationServiceTest { List events = new ArrayList<>(); writeSql("4.3.1.2", "SELECT 1;"); writeSql("4.3.1.3", "SELECT 2;"); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( recordingMigration("4.3.1.2", events), recordingMigration("4.3.1.3", events))); Runnable afterSchemaPhase = () -> events.add("replay"); @@ -447,7 +447,7 @@ class LtsMigrationServiceTest { @Test void applyMigrationsWithReplayNeverRunsBackfillOrReturnsWhenReplayThrows() { List events = new ArrayList<>(); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( recordingMigration("4.3.1.2", events), recordingMigration("4.3.1.3", events))); Runnable afterSchemaPhase = () -> { throw new IllegalStateException("replay failed"); }; @@ -461,12 +461,12 @@ class LtsMigrationServiceTest { @Test void applyMigrationsReturnsNothingWhenALaterBackfillFailsEvenIfAnEarlierOneSucceeded() { List events = new ArrayList<>(); - LtsMigration first = recordingMigration("4.3.1.2", events); - LtsMigration second = new LtsMigration() { + Migration first = recordingMigration("4.3.1.2", events); + Migration second = new Migration() { @Override public String getVersion() { return "4.3.1.3"; } @Override public void applyAfterCommit() { throw new IllegalStateException("backfill failed"); } }; - LtsMigrationService service = service(List.of(first, second)); + MigrationService service = service(List.of(first, second)); // applyMigrations only returns its applied-versions list on a normal return; the second backfill throws // before that return, so the caller never learns the first one succeeded either, and recordVersions is @@ -481,7 +481,7 @@ class LtsMigrationServiceTest { @Test void runDataMigrationsRunsApplyThenAfterCommit() { List events = new ArrayList<>(); - LtsMigrationService service = service(List.of(recordingMigration("4.3.1.3", events))); + MigrationService service = service(List.of(recordingMigration("4.3.1.3", events))); service.runDataMigrations("4.3.1.2", "4.3.1.3", false); @@ -505,7 +505,7 @@ class LtsMigrationServiceTest { @Test void applyMigrationsRunsAllApplyThenAfterSchemaPhaseThenAllApplyAfterCommit() { List sequence = new ArrayList<>(); - LtsMigrationService service = service(List.of( + MigrationService service = service(List.of( migrationWithAfterCommit("4.2.2.3", sequence), migrationWithAfterCommit("4.2.2.4", sequence))); Runnable afterSchemaPhase = () -> sequence.add("afterSchemaPhase"); diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/V4_3_1_5MigrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_3_1_5MigrationTest.java index 5bb0bb642e..c8ea0407c6 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/V4_3_1_5MigrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_3_1_5MigrationTest.java @@ -69,7 +69,7 @@ class V4_3_1_5MigrationTest { } /** - * {@link LtsMigration#apply()} re-runs when a node crashes before the version is recorded, so a key that already + * {@link Migration#apply()} re-runs when a node crashes before the version is recorded, so a key that already * carries the operation must not be written again. */ @Test diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsVersionTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/VersionTest.java similarity index 59% rename from application/src/test/java/org/thingsboard/server/service/install/lts/LtsVersionTest.java rename to application/src/test/java/org/thingsboard/server/service/install/lts/VersionTest.java index 82d7f0c76e..f5f352bb7f 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsVersionTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/VersionTest.java @@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -class LtsVersionTest { +class VersionTest { @ParameterizedTest @CsvSource({ @@ -24,7 +24,7 @@ class LtsVersionTest { "10.20.30.40, 10, 20, 30, 40" }) void parsesValidVersions(String input, int major, int minor, int maintenance, int patch) { - LtsVersion v = LtsVersion.parse(input); + Version v = Version.parse(input); assertEquals(major, v.major()); assertEquals(minor, v.minor()); assertEquals(maintenance, v.maintenance()); @@ -34,32 +34,32 @@ class LtsVersionTest { @ParameterizedTest @ValueSource(strings = {"invalid", "a.b.c", "1.2.y.x", "1.x.3", ""}) void throwsOnInvalidVersions(String input) { - assertThrows(IllegalArgumentException.class, () -> LtsVersion.parse(input)); + assertThrows(IllegalArgumentException.class, () -> Version.parse(input)); } @Test void throwsOnNull() { - assertThrows(IllegalArgumentException.class, () -> LtsVersion.parse(null)); + assertThrows(IllegalArgumentException.class, () -> Version.parse(null)); } @Test void comparesByEachComponent() { - assertTrue(LtsVersion.parse("4.2.2.3").compareTo(LtsVersion.parse("4.2.2.2")) > 0); - assertTrue(LtsVersion.parse("4.2.2.0").compareTo(LtsVersion.parse("4.2.1.9")) > 0); - assertTrue(LtsVersion.parse("4.3.0.0").compareTo(LtsVersion.parse("4.2.9.9")) > 0); - assertEquals(0, LtsVersion.parse("4.2.2.3").compareTo(LtsVersion.parse("4.2.2.3"))); + assertTrue(Version.parse("4.2.2.3").compareTo(Version.parse("4.2.2.2")) > 0); + assertTrue(Version.parse("4.2.2.0").compareTo(Version.parse("4.2.1.9")) > 0); + assertTrue(Version.parse("4.3.0.0").compareTo(Version.parse("4.2.9.9")) > 0); + assertEquals(0, Version.parse("4.2.2.3").compareTo(Version.parse("4.2.2.3"))); } @Test void sameFamilyComparesMajorAndMinorOnly() { - assertTrue(LtsVersion.parse("4.2.2.3").sameFamily(LtsVersion.parse("4.2.0.0"))); - assertFalse(LtsVersion.parse("4.3.0.0").sameFamily(LtsVersion.parse("4.2.9.9"))); - assertFalse(LtsVersion.parse("5.2.0.0").sameFamily(LtsVersion.parse("4.2.0.0"))); + assertTrue(Version.parse("4.2.2.3").sameFamily(Version.parse("4.2.0.0"))); + assertFalse(Version.parse("4.3.0.0").sameFamily(Version.parse("4.2.9.9"))); + assertFalse(Version.parse("5.2.0.0").sameFamily(Version.parse("4.2.0.0"))); } @Test void toStringIsFourComponentDotForm() { - assertEquals("4.2.2.3", LtsVersion.parse("4.2.2.3").toString()); - assertEquals("4.2.0.0", LtsVersion.parse("4.2").toString()); + assertEquals("4.2.2.3", Version.parse("4.2.2.3").toString()); + assertEquals("4.2.0.0", Version.parse("4.2").toString()); } } diff --git a/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java index 201da09a4e..2e8020df80 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java @@ -32,7 +32,7 @@ import org.thingsboard.server.service.component.ComponentDiscoveryService; import org.thingsboard.server.service.install.DatabaseSchemaSettingsService; import org.thingsboard.server.service.install.DbUpgradeExecutorService; import org.thingsboard.server.service.install.SystemDataLoaderService; -import org.thingsboard.server.service.install.lts.LtsMigrationService; +import org.thingsboard.server.service.install.lts.MigrationService; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; @@ -42,7 +42,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * The CE-to-PE conversion is a step on the way to the package version, not an alternative to it: the LTS data + * The CE-to-PE conversion is a step on the way to the package version, not an alternative to it: the migration data * migrations have to run on a converted CE database too, or the conversion silently skips every data migration * between the CE source version and the package version. */ @@ -88,34 +88,34 @@ class DefaultDataUpdateServiceTest { @Mock private DatabaseSchemaSettingsService schemaSettingsService; @Mock - private LtsMigrationService ltsMigrationService; + private MigrationService migrationService; @InjectMocks private DefaultDataUpdateService service; @Test - void ceToPeUpgradeRunsTheLtsDataMigrationsAfterTheConversion() throws Exception { + void ceToPeUpgradeRunsTheDataMigrationsAfterTheConversion() throws Exception { givenAnEmptyDatabase(); service.updateData(true); - InOrder inOrder = inOrder(tenantService, ltsMigrationService); + InOrder inOrder = inOrder(tenantService, migrationService); inOrder.verify(tenantService, atLeastOnce()).findTenants(any(PageLink.class)); - inOrder.verify(ltsMigrationService).runDataMigrations(DB_VERSION, PACKAGE_VERSION, false); + inOrder.verify(migrationService).runDataMigrations(DB_VERSION, PACKAGE_VERSION, false); } @Test - void peUpgradeRunsOnlyTheLtsDataMigrations() throws Exception { + void peUpgradeRunsOnlyTheDataMigrations() throws Exception { givenAnEmptyDatabase(); service.updateData(false); verify(tenantService, never()).findTenants(any(PageLink.class)); - verify(ltsMigrationService).runDataMigrations(DB_VERSION, PACKAGE_VERSION, false); + verify(migrationService).runDataMigrations(DB_VERSION, PACKAGE_VERSION, false); } @Test - void aForcedReUpgradeIsCarriedIntoTheLtsMigrations() throws Exception { + void aForcedReUpgradeIsCarriedIntoTheMigrations() throws Exception { // The only test that can tell the flag apart from a hard-coded false: everywhere else it is Mockito's // default that the assertion reads back. givenAnEmptyDatabase(); @@ -123,7 +123,7 @@ class DefaultDataUpdateServiceTest { service.updateData(false); - verify(ltsMigrationService).runDataMigrations(DB_VERSION, PACKAGE_VERSION, true); + verify(migrationService).runDataMigrations(DB_VERSION, PACKAGE_VERSION, true); } private void givenAnEmptyDatabase() { diff --git a/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java b/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java index 53d4b887b7..a5589b36ce 100644 --- a/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java +++ b/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java @@ -29,7 +29,7 @@ import org.thingsboard.server.dao.widget.WidgetTypeService; import org.thingsboard.server.dao.widget.WidgetsBundleService; import org.thingsboard.server.service.install.DatabaseSchemaSettingsService; import org.thingsboard.server.service.install.InstallScripts; -import org.thingsboard.server.service.install.lts.LtsMigrationService; +import org.thingsboard.server.service.install.lts.MigrationService; import org.thingsboard.server.service.system.SystemPatchApplier; import java.nio.charset.StandardCharsets; @@ -84,7 +84,7 @@ public class SystemPatchApplierTest { private ImageService imageService; @Mock - private LtsMigrationService ltsMigrationService; + private MigrationService migrationService; @InjectMocks private SystemPatchApplier reconciler; @@ -492,7 +492,7 @@ public class SystemPatchApplierTest { // nested back inside that callback (round-1's defect), none of the three calls below would happen at all, // so this also proves the legs are NOT reached through it. List appliedVersions = List.of("4.3.1.0"); - when(ltsMigrationService.applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), eq(false), any())).thenReturn(appliedVersions); + when(migrationService.applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), eq(false), any())).thenReturn(appliedVersions); ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); @@ -500,12 +500,12 @@ public class SystemPatchApplierTest { // call returns and strictly before recordVersions and the final stamp, so a sync failure still blocks the // stamp instead of racing past it. Each leg's signal sits on a different mock, so one InOrder pins all three // at once. - InOrder inOrder = inOrder(ltsMigrationService, widgetTypeService, widgetsBundleService, imageService, schemaSettingsService); - inOrder.verify(ltsMigrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), eq(false), any()); + InOrder inOrder = inOrder(migrationService, widgetTypeService, widgetsBundleService, imageService, schemaSettingsService); + inOrder.verify(migrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), eq(false), any()); inOrder.verify(widgetTypeService).saveWidgetType(argThat(w -> "new_widget".equals(w.getFqn()))); inOrder.verify(widgetsBundleService).saveWidgetsBundle(argThat(b -> "New Title".equals(b.getTitle()))); inOrder.verify(imageService).createOrUpdateSystemImage(eq("new_icon.svg"), eq(imageBytes)); - inOrder.verify(ltsMigrationService).recordVersions(appliedVersions); + inOrder.verify(migrationService).recordVersions(appliedVersions); inOrder.verify(schemaSettingsService).updateSchemaVersion(); } @@ -524,7 +524,7 @@ public class SystemPatchApplierTest { ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); ArgumentCaptor betweenPhases = ArgumentCaptor.forClass(Runnable.class); - verify(ltsMigrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), eq(false), betweenPhases.capture()); + verify(migrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), eq(false), betweenPhases.capture()); String schemaViewsSql = Resources.toString(Resources.getResource("sql/schema-views.sql"), StandardCharsets.UTF_8); String schemaFunctionsSql = Resources.toString(Resources.getResource("sql/schema-functions.sql"), StandardCharsets.UTF_8); @@ -558,7 +558,7 @@ public class SystemPatchApplierTest { assertThrows(RuntimeException.class, () -> ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded")); - verify(ltsMigrationService, never()).recordVersions(any()); + verify(migrationService, never()).recordVersions(any()); verify(schemaSettingsService, never()).updateSchemaVersion(); } @@ -602,8 +602,8 @@ public class SystemPatchApplierTest { ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); - InOrder inOrder = inOrder(ltsMigrationService, schemaSettingsService); - inOrder.verify(ltsMigrationService).applyMigrations(eq("4.3.1.0"), eq("4.3.2.0"), eq(false), any()); + InOrder inOrder = inOrder(migrationService, schemaSettingsService); + inOrder.verify(migrationService).applyMigrations(eq("4.3.1.0"), eq("4.3.2.0"), eq(false), any()); inOrder.verify(schemaSettingsService).updateSchemaVersion(); } diff --git a/common/actor/pom.xml b/common/actor/pom.xml index d1f4eda97b..fa3037517c 100644 --- a/common/actor/pom.xml +++ b/common/actor/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/agent-api/pom.xml b/common/agent-api/pom.xml index 648bab6df3..4b52297231 100644 --- a/common/agent-api/pom.xml +++ b/common/agent-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/cache/pom.xml b/common/cache/pom.xml index 5b476b30cc..0c4ca035a0 100644 --- a/common/cache/pom.xml +++ b/common/cache/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/cluster-api/pom.xml b/common/cluster-api/pom.xml index 64c3d49d39..b3fa8eaf6d 100644 --- a/common/cluster-api/pom.xml +++ b/common/cluster-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml index 50347cb551..fd8a22fd53 100644 --- a/common/coap-server/pom.xml +++ b/common/coap-server/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/dao-api/pom.xml b/common/dao-api/pom.xml index 72b0c0fe97..acb473d00a 100644 --- a/common/dao-api/pom.xml +++ b/common/dao-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common @@ -42,6 +42,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + jakarta.annotation jakarta.annotation-api diff --git a/common/data/pom.xml b/common/data/pom.xml index 815bf191f7..9028a00497 100644 --- a/common/data/pom.xml +++ b/common/data/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common @@ -82,6 +82,10 @@ com.squareup.wire wire-schema-jvm + + org.checkerframework + checker-qual + org.thingsboard protobuf-dynamic diff --git a/common/discovery-api/pom.xml b/common/discovery-api/pom.xml index d7cb25266b..aba7b8e3b7 100644 --- a/common/discovery-api/pom.xml +++ b/common/discovery-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/pom.xml b/common/edge-api/pom.xml index 77005c642c..59c665b07c 100644 --- a/common/edge-api/pom.xml +++ b/common/edge-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 0c17d43e5f..0859747878 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -52,7 +52,7 @@ enum EdgeVersion { V_4_3_1_6 = 4316; V_4_3_1_7 = 4317; V_4_4_0 = 4400; - V_4_4_0_1 = 4401; + V_4_4_1 = 4410; V_LATEST = 99999; } diff --git a/common/edqs/pom.xml b/common/edqs/pom.xml index c4806872cd..b9e850af8c 100644 --- a/common/edqs/pom.xml +++ b/common/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/integration/apache-pulsar/pom.xml b/common/integration/apache-pulsar/pom.xml index 8d2bcb44c1..610872f5e9 100644 --- a/common/integration/apache-pulsar/pom.xml +++ b/common/integration/apache-pulsar/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/aws-integrations/pom.xml b/common/integration/aws-integrations/pom.xml index 7629907753..d313be19bc 100644 --- a/common/integration/aws-integrations/pom.xml +++ b/common/integration/aws-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/azure-integrations/pom.xml b/common/integration/azure-integrations/pom.xml index dad9f38033..8fd70d9c54 100644 --- a/common/integration/azure-integrations/pom.xml +++ b/common/integration/azure-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/cluster-integration-api/pom.xml b/common/integration/cluster-integration-api/pom.xml index 151d787c23..1d4596b74d 100644 --- a/common/integration/cluster-integration-api/pom.xml +++ b/common/integration/cluster-integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/coap-integrations/pom.xml b/common/integration/coap-integrations/pom.xml index f75a62aed9..b00bcb6d09 100644 --- a/common/integration/coap-integrations/pom.xml +++ b/common/integration/coap-integrations/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/gcloud-integrations/pom.xml b/common/integration/gcloud-integrations/pom.xml index b909cfb628..472aeefa9d 100644 --- a/common/integration/gcloud-integrations/pom.xml +++ b/common/integration/gcloud-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/http-integrations/pom.xml b/common/integration/http-integrations/pom.xml index 5b2606505a..c476648e2a 100644 --- a/common/integration/http-integrations/pom.xml +++ b/common/integration/http-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/integration-api/pom.xml b/common/integration/integration-api/pom.xml index 23fbb4f012..15617a0a3a 100644 --- a/common/integration/integration-api/pom.xml +++ b/common/integration/integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/kafka-integrations/pom.xml b/common/integration/kafka-integrations/pom.xml index 1da4a2e5bc..a6604aaa9b 100644 --- a/common/integration/kafka-integrations/pom.xml +++ b/common/integration/kafka-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/mqtt-integrations/pom.xml b/common/integration/mqtt-integrations/pom.xml index 2880ab2710..89b3025891 100644 --- a/common/integration/mqtt-integrations/pom.xml +++ b/common/integration/mqtt-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/opcua-integrations/pom.xml b/common/integration/opcua-integrations/pom.xml index af25e34904..79302fd0ec 100644 --- a/common/integration/opcua-integrations/pom.xml +++ b/common/integration/opcua-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/pom.xml b/common/integration/pom.xml index ffc4d21947..3ee67d5101 100644 --- a/common/integration/pom.xml +++ b/common/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/integration/rabbitmq-integrations/pom.xml b/common/integration/rabbitmq-integrations/pom.xml index c4f120c054..ac28a4cd67 100644 --- a/common/integration/rabbitmq-integrations/pom.xml +++ b/common/integration/rabbitmq-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/remote-integration-api/pom.xml b/common/integration/remote-integration-api/pom.xml index a0efa16741..2db388a166 100644 --- a/common/integration/remote-integration-api/pom.xml +++ b/common/integration/remote-integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/tuya-integrations/pom.xml b/common/integration/tuya-integrations/pom.xml index 6bb785b285..11805ef149 100644 --- a/common/integration/tuya-integrations/pom.xml +++ b/common/integration/tuya-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/message/pom.xml b/common/message/pom.xml index 7fdcc5d7e3..05f4d7a4ea 100644 --- a/common/message/pom.xml +++ b/common/message/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/pom.xml b/common/pom.xml index dd7abf9c65..ecef58c721 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard common diff --git a/common/proto/pom.xml b/common/proto/pom.xml index f27ab28dd3..aef6f29b72 100644 --- a/common/proto/pom.xml +++ b/common/proto/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/queue/pom.xml b/common/queue/pom.xml index 1107cb9d80..be14683ec3 100644 --- a/common/queue/pom.xml +++ b/common/queue/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/report/pom.xml b/common/report/pom.xml index 4c5569f5b3..7aa634f468 100644 --- a/common/report/pom.xml +++ b/common/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/report/src/main/java/org/thingsboard/server/report/datasource/RemoteReportDataService.java b/common/report/src/main/java/org/thingsboard/server/report/datasource/RemoteReportDataService.java index c018879372..a2ad2bce0d 100644 --- a/common/report/src/main/java/org/thingsboard/server/report/datasource/RemoteReportDataService.java +++ b/common/report/src/main/java/org/thingsboard/server/report/datasource/RemoteReportDataService.java @@ -4,6 +4,7 @@ package org.thingsboard.server.report.datasource; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.RestClientResponseException; import org.thingsboard.common.util.JacksonUtil; @@ -32,6 +33,7 @@ import org.thingsboard.server.report.context.TbReportCtx; import java.io.IOException; import java.util.Collection; +import java.util.Collections; import java.util.List; import static org.thingsboard.server.common.data.report.configuration.timewindow.TimeIntervalCalculator.getIntervalTs; @@ -125,6 +127,9 @@ public class RemoteReportDataService implements ReportDataService { try { return getRestClient(ctx).getTimeseries(entityId, keys, getIntervalTs(interval), getIntervalType(interval), timeZone, agg, sortOrder, startTs, endTs, limit, useStrictDataTypes); } catch (RestClientResponseException e) { + if (e.getStatusCode().value() == HttpStatus.FORBIDDEN.value()) { + return Collections.emptyList(); + } throw handleRestClientException(e); } } @@ -134,6 +139,9 @@ public class RemoteReportDataService implements ReportDataService { try { return getRestClient(ctx).getTimeseriesByQueries(entityId, queries); } catch (RestClientResponseException e) { + if (e.getStatusCode().value() == HttpStatus.FORBIDDEN.value()) { + return Collections.emptyList(); + } throw handleRestClientException(e); } } diff --git a/common/script/pom.xml b/common/script/pom.xml index 4c65c0ad49..2fa3adae61 100644 --- a/common/script/pom.xml +++ b/common/script/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/script/remote-js-client/pom.xml b/common/script/remote-js-client/pom.xml index 8107306a8c..d04821e04f 100644 --- a/common/script/remote-js-client/pom.xml +++ b/common/script/remote-js-client/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT script org.thingsboard.common.script diff --git a/common/script/script-api/pom.xml b/common/script/script-api/pom.xml index 59d85f86a1..081a2f3976 100644 --- a/common/script/script-api/pom.xml +++ b/common/script/script-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT script org.thingsboard.common.script diff --git a/common/stats/pom.xml b/common/stats/pom.xml index 53cc5e4eaf..2873f94f9c 100644 --- a/common/stats/pom.xml +++ b/common/stats/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/coap/pom.xml b/common/transport/coap/pom.xml index fe30177622..9a28d7c95c 100644 --- a/common/transport/coap/pom.xml +++ b/common/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/http/pom.xml b/common/transport/http/pom.xml index 577da5ed0c..f9f462da66 100644 --- a/common/transport/http/pom.xml +++ b/common/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml index 3a195d23eb..ccc051900f 100644 --- a/common/transport/lwm2m/pom.xml +++ b/common/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapConfigStoreTaskProvider.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapConfigStoreTaskProvider.java index e9c0ef6dee..cc38b2e502 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapConfigStoreTaskProvider.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/store/LwM2MBootstrapConfigStoreTaskProvider.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.transport.lwm2m.bootstrap.store; import lombok.extern.slf4j.Slf4j; @@ -70,8 +71,10 @@ public class LwM2MBootstrapConfigStoreTaskProvider implements LwM2MBootstrapTask } if (previousResponse == null && shouldStartWithDiscover(configNew)) { Tasks tasks = new Tasks(); - tasks.requestsToSend = new ArrayList<>(1); - tasks.requestsToSend.add(new BootstrapDiscoverRequest()); + tasks.requestsToSend = new ArrayList<>(3); + tasks.requestsToSend.add(new BootstrapDiscoverRequest("/0")); + tasks.requestsToSend.add(new BootstrapDiscoverRequest("/1")); + tasks.requestsToSend.add(new BootstrapDiscoverRequest("/2")); tasks.last = false; return tasks; } else { diff --git a/common/transport/mqtt/pom.xml b/common/transport/mqtt/pom.xml index f10782e394..b499a5f591 100644 --- a/common/transport/mqtt/pom.xml +++ b/common/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/pom.xml b/common/transport/pom.xml index 57728b92b7..103dde135d 100644 --- a/common/transport/pom.xml +++ b/common/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/snmp/pom.xml b/common/transport/snmp/pom.xml index 654180c79a..d3a02e9848 100644 --- a/common/transport/snmp/pom.xml +++ b/common/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index 94160d8e4d..d141135c0d 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/CertificateReloadManager.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/CertificateReloadManager.java index 53ed70ec37..e33b0bd0b2 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/CertificateReloadManager.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/CertificateReloadManager.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.common.transport.service; import lombok.extern.slf4j.Slf4j; @@ -12,7 +13,6 @@ import org.springframework.stereotype.Component; import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.server.common.transport.config.ssl.SslCredentials; import org.thingsboard.server.common.transport.config.ssl.SslCredentialsConfig; -import org.thingsboard.server.queue.util.TbTransportComponent; import java.io.InputStream; import java.nio.file.Files; @@ -30,7 +30,6 @@ import java.util.concurrent.TimeUnit; @Slf4j @Component -@TbTransportComponent public class CertificateReloadManager implements SmartInitializingSingleton, DisposableBean { private static final int MAX_CONSECUTIVE_FAILURES = 10; @@ -143,6 +142,10 @@ public class CertificateReloadManager implements SmartInitializingSingleton, Dis log.info("Initializing Certificate Reload Manager..."); discoverAndRegisterSslCredentials(); + if (watchers.isEmpty()) { + log.debug("No certificate files to watch. Skipping scheduler initialization..."); + return; + } scheduler = Executors.newSingleThreadScheduledExecutor(ThingsBoardThreadFactory.forName("certificate-reload-manager")); scheduler.scheduleWithFixedDelay(this::checkCertificates, checkIntervalInSeconds, checkIntervalInSeconds, TimeUnit.SECONDS); diff --git a/common/transport/transport-api/src/test/java/org/thingsboard/server/common/transport/service/CertificateReloadManagerDiscoveryTest.java b/common/transport/transport-api/src/test/java/org/thingsboard/server/common/transport/service/CertificateReloadManagerDiscoveryTest.java new file mode 100644 index 0000000000..59bfd816fa --- /dev/null +++ b/common/transport/transport-api/src/test/java/org/thingsboard/server/common/transport/service/CertificateReloadManagerDiscoveryTest.java @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.common.transport.service; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.transport.config.ssl.SslCredentials; +import org.thingsboard.server.common.transport.config.ssl.SslCredentialsConfig; + +import java.nio.file.Path; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CertificateReloadManagerDiscoveryTest { + + @TempDir + Path tempDir; + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(CertificateReloadManager.class); + + @Test + public void givenNoSslCredentialsConfigs_whenContextStarts_thenManagerCreatedWithoutScheduler() { + contextRunner.run(context -> { + assertThat(context).hasSingleBean(CertificateReloadManager.class); + assertThat(getScheduler(context.getBean(CertificateReloadManager.class))).isNull(); + }); + } + + @Test + public void givenDisabledSslCredentialsConfig_whenContextStarts_thenSchedulerNotStarted() { + SslCredentialsConfig config = mockSslCredentialsConfig(false, List.of(tempDir.resolve("server.pem"))); + contextRunner + .withBean(SslCredentialsConfig.class, () -> config) + .run(context -> assertThat(getScheduler(context.getBean(CertificateReloadManager.class))).isNull()); + } + + @Test + public void givenSslCredentialsConfigWithCertificateFile_whenContextStarts_thenSchedulerStarted() { + SslCredentialsConfig config = mockSslCredentialsConfig(true, List.of(tempDir.resolve("server.pem"))); + contextRunner + .withBean(SslCredentialsConfig.class, () -> config) + .run(context -> assertThat(getScheduler(context.getBean(CertificateReloadManager.class))).isNotNull()); + } + + @Test + public void givenReloadDisabled_whenContextStarts_thenSchedulerNotStarted() { + SslCredentialsConfig config = mockSslCredentialsConfig(true, List.of(tempDir.resolve("server.pem"))); + contextRunner + .withPropertyValues("transport.ssl.certificate.reload.enabled=false") + .withBean(SslCredentialsConfig.class, () -> config) + .run(context -> assertThat(getScheduler(context.getBean(CertificateReloadManager.class))).isNull()); + } + + private static SslCredentialsConfig mockSslCredentialsConfig(boolean enabled, List certificateFilePaths) { + SslCredentials credentials = mock(SslCredentials.class); + when(credentials.getCertificateFilePaths()).thenReturn(certificateFilePaths); + SslCredentialsConfig config = mock(SslCredentialsConfig.class); + when(config.isEnabled()).thenReturn(enabled); + when(config.getName()).thenReturn("Test SSL Credentials"); + when(config.getCredentials()).thenReturn(credentials); + return config; + } + + private static Object getScheduler(CertificateReloadManager manager) { + return ReflectionTestUtils.getField(manager, "scheduler"); + } + +} diff --git a/common/util/pom.xml b/common/util/pom.xml index 38dafbf900..0fe6b896a4 100644 --- a/common/util/pom.xml +++ b/common/util/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common diff --git a/common/version-control/pom.xml b/common/version-control/pom.xml index 0691144f3d..1b80246053 100644 --- a/common/version-control/pom.xml +++ b/common/version-control/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT common org.thingsboard.common @@ -59,6 +59,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + com.fasterxml.jackson.core jackson-databind diff --git a/dao/pom.xml b/dao/pom.xml index 1330f42cda..2d84a22298 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard dao @@ -170,6 +170,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + com.google.protobuf protobuf-java diff --git a/dao/src/main/java/org/thingsboard/server/dao/housekeeper/CleanUpService.java b/dao/src/main/java/org/thingsboard/server/dao/housekeeper/CleanUpService.java index 3c2c93e0a9..44dea223bb 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/housekeeper/CleanUpService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/housekeeper/CleanUpService.java @@ -11,6 +11,7 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.event.TransactionalEventListener; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.housekeeper.HousekeeperTask; import org.thingsboard.server.common.data.id.AlarmId; import org.thingsboard.server.common.data.id.EntityId; @@ -61,9 +62,10 @@ public class CleanUpService { if (entityType == EntityType.TENANT) { submitTask(HousekeeperTask.deleteAiTenantData(tenantId)); } - if (entityType == EntityType.ALARM && event.getCause() != ActionCause.BULK_DELETION) { + if (entityType == EntityType.ALARM && event.getEntity() instanceof Alarm && event.getCause() != ActionCause.BULK_DELETION) { // Single-alarm delete: clean up its comments per alarm. Bulk deletions (BULK_DELETION) batch the // comment cleanup into a single list task at the orchestrator instead, to avoid one task per alarm. + // The entity check matters: deleting a single alarm comment publishes the same event with the alarm id. submitTask(HousekeeperTask.deleteAlarmComments(tenantId, new AlarmId(entityId.getId()))); } } catch (Throwable e) { diff --git a/dao/src/main/resources/sql/schema-entities.sql b/dao/src/main/resources/sql/schema-entities.sql index 987c852ed0..0f55b4fae0 100644 --- a/dao/src/main/resources/sql/schema-entities.sql +++ b/dao/src/main/resources/sql/schema-entities.sql @@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS tb_instance_registry ( last_activity_ts bigint NOT NULL ); --- Also copied by the upgrade scripts that reach this table; LtsMigrationIntegrationTest keeps them in sync. +-- Also copied by the upgrade scripts that reach this table; MigrationIntegrationTest keeps them in sync. CREATE TABLE IF NOT EXISTS tb_cluster ( cluster_id uuid NOT NULL, license_secret varchar, diff --git a/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTest.java index 98ed202a11..ed66d2b6d2 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTest.java @@ -7,8 +7,10 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; +import org.thingsboard.server.common.data.alarm.AlarmComment; import org.thingsboard.server.common.data.housekeeper.HousekeeperTask; import org.thingsboard.server.common.data.housekeeper.HousekeeperTaskType; +import org.thingsboard.server.common.data.id.AlarmCommentId; import org.thingsboard.server.common.data.id.AlarmId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; @@ -70,6 +72,7 @@ class CleanUpServiceTest { DeleteEntityEvent event = DeleteEntityEvent.builder() .tenantId(tenantId) .entityId(alarmId) + .entity(new Alarm(alarmId)) .build(); cleanUpService.handleEntityDeletionEvent(event); @@ -90,12 +93,29 @@ class CleanUpServiceTest { verify(relationService, never()).deleteEntityRelations(tenantId, alarmId); } + @Test + void alarmCommentDeletionDoesNotEnqueueAlarmCommentsCleanupTask() { + AlarmId alarmId = new AlarmId(UUID.randomUUID()); + AlarmComment alarmComment = new AlarmComment(new AlarmCommentId(UUID.randomUUID())); + alarmComment.setAlarmId(alarmId); + DeleteEntityEvent event = DeleteEntityEvent.builder() + .tenantId(tenantId) + .entityId(alarmId) + .entity(alarmComment) + .build(); + + cleanUpService.handleEntityDeletionEvent(event); + + verify(housekeeperClient, never()).submitTask(any()); + } + @Test void bulkAlarmDeletionDoesNotEnqueuePerAlarmCommentsCleanupTask() { AlarmId alarmId = new AlarmId(UUID.randomUUID()); DeleteEntityEvent event = DeleteEntityEvent.builder() .tenantId(tenantId) .entityId(alarmId) + .entity(new Alarm(alarmId)) .cause(ActionCause.BULK_DELETION) .build(); diff --git a/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTransactionalTest.java b/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTransactionalTest.java index 4fd8b2e8f4..de9f2a09e9 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTransactionalTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/housekeeper/CleanUpServiceTransactionalTest.java @@ -79,9 +79,11 @@ public class CleanUpServiceTransactionalTest extends AbstractServiceTest { } private DeleteEntityEvent alarmDeletionEvent() { + AlarmId alarmId = new AlarmId(UUID.randomUUID()); return DeleteEntityEvent.builder() .tenantId(tenantId) - .entityId(new AlarmId(UUID.randomUUID())) + .entityId(alarmId) + .entity(new Alarm(alarmId)) .build(); } diff --git a/edqs/pom.xml b/edqs/pom.xml index 1d6a0c8428..08ad8c6257 100644 --- a/edqs/pom.xml +++ b/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard edqs diff --git a/integration/apache-pulsar/pom.xml b/integration/apache-pulsar/pom.xml index f81588fb8d..933f978139 100644 --- a/integration/apache-pulsar/pom.xml +++ b/integration/apache-pulsar/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/aws/pom.xml b/integration/aws/pom.xml index 41a86f31d3..51ad65f933 100644 --- a/integration/aws/pom.xml +++ b/integration/aws/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/azure/pom.xml b/integration/azure/pom.xml index 86a6a23a29..d568ac3c65 100644 --- a/integration/azure/pom.xml +++ b/integration/azure/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/coap/pom.xml b/integration/coap/pom.xml index caf30f83f2..617763a02a 100644 --- a/integration/coap/pom.xml +++ b/integration/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/coap/src/main/java/org/thingsboard/integration/ThingsboardCoapIntegrationApplication.java b/integration/coap/src/main/java/org/thingsboard/integration/ThingsboardCoapIntegrationApplication.java index 46f419d853..691675e579 100644 --- a/integration/coap/src/main/java/org/thingsboard/integration/ThingsboardCoapIntegrationApplication.java +++ b/integration/coap/src/main/java/org/thingsboard/integration/ThingsboardCoapIntegrationApplication.java @@ -5,13 +5,16 @@ package org.thingsboard.integration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; +import org.thingsboard.server.common.transport.service.CertificateReloadManager; import java.util.Arrays; @SpringBootApplication @EnableAsync @ComponentScan({"org.thingsboard.integration", "org.thingsboard.script.api", "org.thingsboard.server.coapserver"}) +@Import(CertificateReloadManager.class) public class ThingsboardCoapIntegrationApplication { private static final String SPRING_CONFIG_NAME_KEY = "--spring.config.name"; diff --git a/integration/coap/src/main/resources/tb-coap-integration.yml b/integration/coap/src/main/resources/tb-coap-integration.yml index a7fde74529..560f20b9f7 100644 --- a/integration/coap/src/main/resources/tb-coap-integration.yml +++ b/integration/coap/src/main/resources/tb-coap-integration.yml @@ -27,6 +27,8 @@ spring: exclude: - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration - org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration + main: + allow-circular-references: "true" # Spring Boot configuration property that controls whether circular dependencies between beans are allowed. storage: # Location of the folder to store data files @@ -134,14 +136,41 @@ coap: # } MaxFragmentLength; # TLS already requires clients and servers to support fragmentation of handshake messages. max_fragment_length: "${COAP_DTLS_MAX_FRAGMENT_LENGTH:1024}" - # Path to the key store that holds the certificate - key_store: "${COAP_DTLS_KEY_STORE:coapserver.jks}" - # Password used to access the key store - key_store_password: "${COAP_DTLS_KEY_STORE_PASSWORD:server_ks_password}" - # Password used to access the key - key_password: "${COAP_DTLS_KEY_PASSWORD:server_key_password}" - # Key alias - key_alias: "${COAP_DTLS_KEY_ALIAS:serveralias}" + # Server DTLS credentials + credentials: + # Server credentials type (PEM - pem certificate file; KEYSTORE - java keystore) + type: "${COAP_DTLS_CREDENTIALS_TYPE:PEM}" + # PEM server credentials + pem: + # Path to the server certificate file (holds server certificate or certificate chain, may include server private key) + cert_file: "${COAP_DTLS_PEM_CERT:coapserver.pem}" + # Path to the server certificate private key file. Optional by default. Required if the private key is not present in server certificate file; + key_file: "${COAP_DTLS_PEM_KEY:coapserver_key.pem}" + # Server certificate private key password (optional) + key_password: "${COAP_DTLS_PEM_KEY_PASSWORD:server_key_password}" + # Keystore server credentials + keystore: + # Type of the key store (JKS or PKCS12) + type: "${COAP_DTLS_KEY_STORE_TYPE:JKS}" + # Path to the key store that holds the SSL certificate + store_file: "${COAP_DTLS_KEY_STORE:coapserver.jks}" + # Password used to access the key store + store_password: "${COAP_DTLS_KEY_STORE_PASSWORD:server_ks_password}" + # Key alias + key_alias: "${COAP_DTLS_KEY_ALIAS:serveralias}" + # Password used to access the key + key_password: "${COAP_DTLS_KEY_PASSWORD:server_key_password}" + +transport: + ssl: + # SSL/TLS settings + certificate: + # X.509 certificate configuration to auto-detect and reload certificate used by the CoAP server (DTLS) in real-time + reload: + # Enable/disable automatic SSL certificates reload + enabled: "${TB_TRANSPORT_SSL_CERTIFICATE_RELOAD_ENABLED:true}" + # Check interval in seconds for certificates reload + check_interval_seconds: "${TB_TRANSPORT_SSL_CERTIFICATE_RELOAD_CHECK_INTERVAL_SECONDS:60}" service: - type: "${TB_SERVICE_TYPE:tb-integration}" \ No newline at end of file + type: "${TB_SERVICE_TYPE:tb-integration}" diff --git a/integration/executor/pom.xml b/integration/executor/pom.xml index 41a281d9f9..4854543122 100644 --- a/integration/executor/pom.xml +++ b/integration/executor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/executor/src/main/resources/tb-integration-executor.yml b/integration/executor/src/main/resources/tb-integration-executor.yml index de77beb11c..7e2f6d107c 100644 --- a/integration/executor/src/main/resources/tb-integration-executor.yml +++ b/integration/executor/src/main/resources/tb-integration-executor.yml @@ -429,14 +429,23 @@ js: # Interval of logging for remote JS executor stats print_interval_ms: "${TB_JS_REMOTE_STATS_PRINT_INTERVAL_MS:10000}" -# JSON converter parameters -# Controls JSON telemetry/attribute parsing behaviour, including type casting and maximum string value length. +# JSON converter and SSL certificate reload parameters +# Controls JSON telemetry/attribute parsing behaviour, including type casting and maximum string value length, and real-time reload of CoAP DTLS certificates. transport: json: # Cast String data types to Numeric if possible when processing Telemetry/Attributes JSON type_cast_enabled: "${JSON_TYPE_CAST_ENABLED:true}" # Maximum allowed string value length when processing Telemetry/Attributes JSON (0 value disables string value length check) max_string_value_length: "${JSON_MAX_STRING_VALUE_LENGTH:0}" + ssl: + # SSL/TLS settings + certificate: + # X.509 certificate configuration to auto-detect and reload certificate used by the CoAP server (DTLS) in real-time + reload: + # Enable/disable automatic SSL certificates reload + enabled: "${TB_TRANSPORT_SSL_CERTIFICATE_RELOAD_ENABLED:true}" + # Check interval in seconds for certificates reload + check_interval_seconds: "${TB_TRANSPORT_SSL_CERTIFICATE_RELOAD_CHECK_INTERVAL_SECONDS:60}" # Cache parameters # Configures the cache backend type (Caffeine or Redis) and per-cache TTL and size limits. diff --git a/integration/http/pom.xml b/integration/http/pom.xml index 1d619ab324..d83c8b52d1 100644 --- a/integration/http/pom.xml +++ b/integration/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/kafka/pom.xml b/integration/kafka/pom.xml index 28e498fa45..168c9f5a68 100644 --- a/integration/kafka/pom.xml +++ b/integration/kafka/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/mqtt/pom.xml b/integration/mqtt/pom.xml index 2bc8af134e..1ab8dec89e 100644 --- a/integration/mqtt/pom.xml +++ b/integration/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/opc-ua/pom.xml b/integration/opc-ua/pom.xml index e1ae8ffc85..3332c6462d 100644 --- a/integration/opc-ua/pom.xml +++ b/integration/opc-ua/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/pom.xml b/integration/pom.xml index 2f3ec66166..e4df184899 100644 --- a/integration/pom.xml +++ b/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard integration diff --git a/integration/pubsub/pom.xml b/integration/pubsub/pom.xml index 286d29f1bc..d571e3c5b3 100644 --- a/integration/pubsub/pom.xml +++ b/integration/pubsub/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/rabbitmq/pom.xml b/integration/rabbitmq/pom.xml index 081147ad5a..3b286f1c5d 100644 --- a/integration/rabbitmq/pom.xml +++ b/integration/rabbitmq/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/tcp-udp/pom.xml b/integration/tcp-udp/pom.xml index 1ae99f25ef..4f0c360e97 100644 --- a/integration/tcp-udp/pom.xml +++ b/integration/tcp-udp/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/tuya/pom.xml b/integration/tuya/pom.xml index 1d84b18221..3057a6df39 100644 --- a/integration/tuya/pom.xml +++ b/integration/tuya/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration org.thingsboard.integration diff --git a/migrator/pom.xml b/migrator/pom.xml index 7de06d3f90..fcf5838720 100644 --- a/migrator/pom.xml +++ b/migrator/pom.xml @@ -12,7 +12,7 @@ thingsboard org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT migrator diff --git a/monitoring/pom.xml b/monitoring/pom.xml index 53c5d3ec8a..5225aea050 100644 --- a/monitoring/pom.xml +++ b/monitoring/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard diff --git a/msa/black-box-tests/pom.xml b/msa/black-box-tests/pom.xml index 82d4ca6810..03077a442e 100644 --- a/msa/black-box-tests/pom.xml +++ b/msa/black-box-tests/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/edqs/pom.xml b/msa/edqs/pom.xml index 19129f8365..5fc1650d80 100644 --- a/msa/edqs/pom.xml +++ b/msa/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/integration/apache-pulsar/pom.xml b/msa/integration/apache-pulsar/pom.xml index be95124a98..c4e9cb8263 100644 --- a/msa/integration/apache-pulsar/pom.xml +++ b/msa/integration/apache-pulsar/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/aws/pom.xml b/msa/integration/aws/pom.xml index 42c4cc38fa..1afd9aad25 100644 --- a/msa/integration/aws/pom.xml +++ b/msa/integration/aws/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/azure/pom.xml b/msa/integration/azure/pom.xml index da528c71ec..e306620b71 100644 --- a/msa/integration/azure/pom.xml +++ b/msa/integration/azure/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/coap/pom.xml b/msa/integration/coap/pom.xml index 06059a5e01..81155bc7e9 100644 --- a/msa/integration/coap/pom.xml +++ b/msa/integration/coap/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/executor/pom.xml b/msa/integration/executor/pom.xml index 24946b9f3e..450271579c 100644 --- a/msa/integration/executor/pom.xml +++ b/msa/integration/executor/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/http/pom.xml b/msa/integration/http/pom.xml index 7041c2c4fd..beb8d3fe31 100644 --- a/msa/integration/http/pom.xml +++ b/msa/integration/http/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/kafka/pom.xml b/msa/integration/kafka/pom.xml index 9d90ca755d..00c1f17501 100644 --- a/msa/integration/kafka/pom.xml +++ b/msa/integration/kafka/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/mqtt/pom.xml b/msa/integration/mqtt/pom.xml index 5095573d29..de56a62159 100644 --- a/msa/integration/mqtt/pom.xml +++ b/msa/integration/mqtt/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/opc-ua/pom.xml b/msa/integration/opc-ua/pom.xml index d6eb1e39b3..2f455d67fd 100644 --- a/msa/integration/opc-ua/pom.xml +++ b/msa/integration/opc-ua/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/pom.xml b/msa/integration/pom.xml index c7debdd00a..4e5a22d2fe 100644 --- a/msa/integration/pom.xml +++ b/msa/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa @@ -110,7 +110,7 @@ - 4.4.0-latest + 4.4.1-latest false diff --git a/msa/integration/pubsub/pom.xml b/msa/integration/pubsub/pom.xml index f1dd1b878e..e9b7bb3975 100644 --- a/msa/integration/pubsub/pom.xml +++ b/msa/integration/pubsub/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/rabbitmq/pom.xml b/msa/integration/rabbitmq/pom.xml index a79d9bfd2a..baa664bea2 100644 --- a/msa/integration/rabbitmq/pom.xml +++ b/msa/integration/rabbitmq/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/tcp-udp/pom.xml b/msa/integration/tcp-udp/pom.xml index ca9e7cf50d..5b47b031eb 100644 --- a/msa/integration/tcp-udp/pom.xml +++ b/msa/integration/tcp-udp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/integration/tuya/pom.xml b/msa/integration/tuya/pom.xml index 434db9bbe6..22ca7ffa7e 100644 --- a/msa/integration/tuya/pom.xml +++ b/msa/integration/tuya/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT integration diff --git a/msa/js-executor/package.json b/msa/js-executor/package.json index f534a6d07b..d88291cf17 100644 --- a/msa/js-executor/package.json +++ b/msa/js-executor/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-js-executor", "private": true, - "version": "4.4.0.1", + "version": "4.4.1", "description": "ThingsBoard JavaScript Executor Microservice", "main": "server.ts", "bin": "server.js", diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index f5b5baf0c9..1e407061a6 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/migrator/pom.xml b/msa/migrator/pom.xml index a6d7ae86a8..bbb29c50f5 100644 --- a/msa/migrator/pom.xml +++ b/msa/migrator/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa diff --git a/msa/monitoring/pom.xml b/msa/monitoring/pom.xml index 0bd2786a49..fb95e91b7d 100644 --- a/msa/monitoring/pom.xml +++ b/msa/monitoring/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa diff --git a/msa/pom.xml b/msa/pom.xml index bfb8655728..43cd606147 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard msa @@ -196,7 +196,7 @@ - 4.4.0-latest + 4.4.1-latest false diff --git a/msa/report/pom.xml b/msa/report/pom.xml index 8a3361d2c3..6a782df30a 100644 --- a/msa/report/pom.xml +++ b/msa/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/tb-node/pom.xml b/msa/tb-node/pom.xml index 8227d7bcb0..0baf11cf45 100644 --- a/msa/tb-node/pom.xml +++ b/msa/tb-node/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/coap/pom.xml b/msa/transport/coap/pom.xml index 1354f57dab..e06e589e5c 100644 --- a/msa/transport/coap/pom.xml +++ b/msa/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/http/pom.xml b/msa/transport/http/pom.xml index 10d593c1ea..6127552381 100644 --- a/msa/transport/http/pom.xml +++ b/msa/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/lwm2m/pom.xml b/msa/transport/lwm2m/pom.xml index 23fcf1aa52..3babb3256f 100644 --- a/msa/transport/lwm2m/pom.xml +++ b/msa/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/mqtt/pom.xml b/msa/transport/mqtt/pom.xml index 682986ec8b..66e483f62e 100644 --- a/msa/transport/mqtt/pom.xml +++ b/msa/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/pom.xml b/msa/transport/pom.xml index 12bba190cf..93c2de38bf 100644 --- a/msa/transport/pom.xml +++ b/msa/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/snmp/pom.xml b/msa/transport/snmp/pom.xml index c96784b765..08c7df6229 100644 --- a/msa/transport/snmp/pom.xml +++ b/msa/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard.msa transport - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT org.thingsboard.msa.transport diff --git a/msa/vc-executor-docker/pom.xml b/msa/vc-executor-docker/pom.xml index db28206847..b401024448 100644 --- a/msa/vc-executor-docker/pom.xml +++ b/msa/vc-executor-docker/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/vc-executor/pom.xml b/msa/vc-executor/pom.xml index f1092bf837..8a7b8e15ca 100644 --- a/msa/vc-executor/pom.xml +++ b/msa/vc-executor/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/web-report/package.json b/msa/web-report/package.json index a4a5433e9e..fe0ec7a8ff 100644 --- a/msa/web-report/package.json +++ b/msa/web-report/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-report", "private": true, - "version": "4.4.0.1", + "version": "4.4.1", "description": "ThingsBoard Web Reporting Microservice", "main": "server.ts", "bin": "server.js", diff --git a/msa/web-report/pom.xml b/msa/web-report/pom.xml index e3d9832b79..05f3813996 100644 --- a/msa/web-report/pom.xml +++ b/msa/web-report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index 1aed9569a1..b1f0b82c9e 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-ui", "private": true, - "version": "4.4.0.1", + "version": "4.4.1", "description": "ThingsBoard Web UI Microservice", "main": "server.ts", "bin": "server.js", diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 652bb2dc5c..5e3d67d99c 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT msa org.thingsboard.msa diff --git a/netty-mqtt/pom.xml b/netty-mqtt/pom.xml index 6733a24fb2..9fe47daa32 100644 --- a/netty-mqtt/pom.xml +++ b/netty-mqtt/pom.xml @@ -9,11 +9,11 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard netty-mqtt - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT jar Netty MQTT Client diff --git a/pom.xml b/pom.xml index 873a098388..e3723c709c 100755 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT pom ThingsBoard @@ -75,12 +75,12 @@ 3.18.0 4.1.138.Final 1.62.0 - 10.1.59 + 10.1.60 5.4.3 1.5.38 2.21.7 - 42.7.12 - 1.11.1 + 42.7.14 + 1.11.4 5.34.0 5.6.4 1.5.7-14 @@ -92,7 +92,7 @@ 4.17.0 4.2.25 5.0.7 - 33.1.0-jre + 33.7.2-jre 2.16.1 1.3.1 1.10.0 @@ -125,7 +125,7 @@ 2.2.30 0.8 1.19.0 - 1.85 + 1.86 2.0.1 1.13.0 0.35.0 @@ -204,7 +204,7 @@ 1.6.1 2.19.0 9.2.0 - 1.1.10.5 + 1.1.10.10 9.10.0 3.1.5.RELEASE 9.13.0 diff --git a/pull_request_template.md b/pull_request_template.md index d375ea4d5f..4d37602ca5 100644 --- a/pull_request_template.md +++ b/pull_request_template.md @@ -5,6 +5,7 @@ Put your PR description here instead of this sentence. ## General checklist - [ ] You have reviewed the [contributing guidelines](https://github.com/thingsboard/thingsboard/blob/master/CONTRIBUTING.md). +- [ ] You have signed the [Contributor License Agreement](https://cla-assistant.io/thingsboard/thingsboard). - [ ] [Labels](https://docs.github.com/en/issues/using-labels-and-milestones-to-track-work/managing-labels#about-labels) that classify your pull request have been added. - [ ] The [milestone](https://docs.github.com/en/issues/using-labels-and-milestones-to-track-work/about-milestones) is specified and corresponds to fix version. - [ ] Description references specific [issue](https://github.com/thingsboard/thingsboard/issues). diff --git a/report/pom.xml b/report/pom.xml index f428e65d22..5344f98b18 100644 --- a/report/pom.xml +++ b/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard report diff --git a/rest-client/pom.xml b/rest-client/pom.xml index 1be733ccee..6ef87dde9b 100644 --- a/rest-client/pom.xml +++ b/rest-client/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard rest-client diff --git a/rule-engine/pom.xml b/rule-engine/pom.xml index 59b274c450..72c1799c23 100644 --- a/rule-engine/pom.xml +++ b/rule-engine/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard rule-engine diff --git a/rule-engine/rule-engine-api/pom.xml b/rule-engine/rule-engine-api/pom.xml index c0eaa24237..9b9ba5f45d 100644 --- a/rule-engine/rule-engine-api/pom.xml +++ b/rule-engine/rule-engine-api/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/rule-engine/rule-engine-components/pom.xml b/rule-engine/rule-engine-components/pom.xml index 312a8396fe..bc6f4b2eef 100644 --- a/rule-engine/rule-engine-components/pom.xml +++ b/rule-engine/rule-engine-components/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT rule-engine org.thingsboard.rule-engine @@ -68,6 +68,10 @@ com.google.guava guava + + org.checkerframework + checker-qual + com.google.code.gson gson diff --git a/tools/pom.xml b/tools/pom.xml index 41d179c115..2acb7b5877 100644 --- a/tools/pom.xml +++ b/tools/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard tools diff --git a/tools/src/main/python/license-headers/curations.json b/tools/src/main/python/license-headers/curations.json index 75b0eb6a2c..cc237af332 100644 --- a/tools/src/main/python/license-headers/curations.json +++ b/tools/src/main/python/license-headers/curations.json @@ -439,6 +439,18 @@ "reason": "PE-specific data/configuration type IntegrationLifecycleEventTrigger.java. Reviewed fields, type discriminators and serialization hooks describe PE entities or PE behavior; matching CE types supply only the common DTO/interface pattern. Resolved as PE-authored consistently with the maintainer decision for PE entity wrappers. Reviewed candidate common/data/src/main/java/org/thingsboard/server/common/data/notification/rule/trigger/RuleEngineComponentLifecycleEventTrigger.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob e4c967c19792ecf5fa6409973459efe5ce73cb8d).", "contentHash": "sha256:c5da9a11ed196635c09972733cf511bee2bd111242c0d084d115d37e2e7524c5" }, + { + "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/targets/platform/UserGroupListFilter.java", + "header": "busl", + "reason": "PE user group filter, a new class with its own groupsIds field and USER_GROUP_LIST type. The similarity comes from the shared shape of small filter DTOs, not from CE code. Reviewed candidate common/data/src/main/java/org/thingsboard/server/common/data/notification/targets/platform/UserListFilter.java at 862b224dd7e4e770804ffad3411255166daa4501 (blob 07cd0280ba84ab71b6823242e18c7c7285296b84).", + "contentHash": "sha256:64563fbc6ee416025b555c14cf3c517c5027bfc112a883078cc717ed471c5b52" + }, + { + "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/targets/platform/UserRoleFilter.java", + "header": "busl", + "reason": "PE role filter, a new class with its own rolesIds field and USER_ROLE type. The similarity comes from the shared shape of small filter DTOs, not from CE code. Reviewed candidate common/data/src/main/java/org/thingsboard/server/common/data/notification/targets/platform/UserListFilter.java at 862b224dd7e4e770804ffad3411255166daa4501 (blob 07cd0280ba84ab71b6823242e18c7c7285296b84).", + "contentHash": "sha256:007e94e798f25a9d0ccd1716b8a68eada4fe3ced71e531bd0538c2c56e24ecb7" + }, { "path": "common/data/src/main/java/org/thingsboard/server/common/data/permission/Operation.java", "header": "ce-modified", @@ -457,6 +469,12 @@ "reason": "PE-specific data/configuration type EntityGroupNameFilter.java. Reviewed fields, type discriminators and serialization hooks describe PE entities or PE behavior; matching CE types supply only the common DTO/interface pattern. Resolved as PE-authored consistently with the maintainer decision for PE entity wrappers. Reviewed candidate common/data/src/main/java/org/thingsboard/server/common/data/query/EntityNameFilter.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob a3889bc7c07de44917eac165a9c4e8578bbbcd62).", "contentHash": "sha256:46cc0073210fb81fb1a71f44604042da6056f78f62468cf45bdc78cdaf8cdd09" }, + { + "path": "common/data/src/main/java/org/thingsboard/server/common/data/query/StateEntityFilter.java", + "header": "busl", + "reason": "PE dashboard state entity filter, a new class with its own defaultStateEntity field and STATE_ENTITY type. The similarity comes from the shared shape of small filter DTOs, not from CE code. Reviewed candidate common/data/src/main/java/org/thingsboard/server/common/data/query/SingleEntityFilter.java at 862b224dd7e4e770804ffad3411255166daa4501 (blob dacd7de6eae6cd80cfd63047dad8951d76aeb455).", + "contentHash": "sha256:46835b82b0320007209a5d53528f9fdb534af41c2fcb5a528754c316c530394a" + }, { "path": "common/data/src/main/java/org/thingsboard/server/common/data/query/StateEntityOwnerFilter.java", "header": "busl", @@ -797,7 +815,7 @@ "path": "integration/coap/src/main/java/org/thingsboard/integration/ThingsboardCoapIntegrationApplication.java", "header": "busl", "reason": "Launch, logging or runtime scaffolding for a PE service. Maintainer explicitly resolved this PE module scaffolding as PE-only; matching CE startup/logging conventions do not override that decision. Reviewed similarity candidate transport/http/src/main/java/org/thingsboard/server/http/ThingsboardHttpTransportApplication.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob 98be09069a487befab217c9b7c036fc6132fc97b).", - "contentHash": "sha256:691ed1e7c96845e81ccfdcf522c836794f4045180c74d50be1613122517397c4" + "contentHash": "sha256:d603f73f715f82368dcfd54325b95c653684077d49afeafb69b9117b7196dfbc" }, { "path": "integration/coap/src/main/resources/logback.xml", diff --git a/transport/coap/pom.xml b/transport/coap/pom.xml index 61002add66..d8226cd117 100644 --- a/transport/coap/pom.xml +++ b/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/http/pom.xml b/transport/http/pom.xml index 744cc2a956..a3257700b1 100644 --- a/transport/http/pom.xml +++ b/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/lwm2m/pom.xml b/transport/lwm2m/pom.xml index 45767f145f..c7ab8fca10 100644 --- a/transport/lwm2m/pom.xml +++ b/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/mqtt/pom.xml b/transport/mqtt/pom.xml index 8654ddf92b..b651546129 100644 --- a/transport/mqtt/pom.xml +++ b/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/pom.xml b/transport/pom.xml index 55e9390896..c308306461 100644 --- a/transport/pom.xml +++ b/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard transport diff --git a/transport/snmp/pom.xml b/transport/snmp/pom.xml index 38d689872f..2ca38942f7 100644 --- a/transport/snmp/pom.xml +++ b/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT transport diff --git a/ui-ngx/package.json b/ui-ngx/package.json index a11a1c4221..0dbbae9f5e 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -1,6 +1,6 @@ { "name": "thingsboard", - "version": "4.4.0.1", + "version": "4.4.1", "scripts": { "ng": "ng", "start": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng serve --configuration development --host 0.0.0.0 --open", diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index a83bbd7864..5442028c2c 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.0.1-SNAPSHOT + 4.4.1-SNAPSHOT thingsboard ui-ngx diff --git a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts index 74d515996f..05f6608ae5 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts @@ -529,9 +529,6 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa toggleEntityDetails($event: Event, entity) { if ($event) { $event.stopPropagation(); - if (($event as MouseEvent).detail > 1) { - return; - } } const open = this.dataSource.toggleCurrentEntity(entity) ? true : !this.isDetailsOpen; this.setEntityDetailsOpen(open); diff --git a/ui-ngx/src/app/modules/home/home.component.scss b/ui-ngx/src/app/modules/home/home.component.scss index d39e640480..6843152ada 100644 --- a/ui-ngx/src/app/modules/home/home.component.scss +++ b/ui-ngx/src/app/modules/home/home.component.scss @@ -166,7 +166,7 @@ } .tb-main-content-wrapper { position: relative; - overflow: hidden; + overflow: clip; flex: 1; display: flex; } diff --git a/ui-ngx/src/app/shared/models/converter.models.ts b/ui-ngx/src/app/shared/models/converter.models.ts index 98187efe93..e953cd1fb1 100644 --- a/ui-ngx/src/app/shared/models/converter.models.ts +++ b/ui-ngx/src/app/shared/models/converter.models.ts @@ -15,7 +15,7 @@ export enum ConverterType { DOWNLINK = 'DOWNLINK' } -export const IntegrationTbelDefaultConvertersUrl = new Map([ +export const IntegrationTbelDefaultDecodersUrl = new Map([ [IntegrationType.CHIRPSTACK, '/assets/converters/tbel-chirpstack-decoder.raw'], [IntegrationType.LORIOT, '/assets/converters/tbel-loriot-decoder.raw'], [IntegrationType.TTI,'/assets/converters/tbel-tti-decoder.raw'], @@ -31,7 +31,7 @@ export const IntegrationTbelDefaultConvertersUrl = new Map([ +export const IntegrationJSDefaultDecodersUrl = new Map([ [IntegrationType.CHIRPSTACK, '/assets/converters/js-chirpstack-decoder.raw'], [IntegrationType.LORIOT, '/assets/converters/js-loriot-decoder.raw'], [IntegrationType.TTI,'/assets/converters/js-tti-decoder.raw'], @@ -42,7 +42,20 @@ export const IntegrationJSDefaultConvertersUrl = new Map([ - [IntegrationType.OPC_UA, '/assets/converters/tbel-opc-ua-encoder.raw'] + [IntegrationType.OPC_UA, '/assets/converters/tbel-opc-ua-encoder.raw'], + [IntegrationType.TTI, '/assets/converters/tbel-ttn-tti-encoder.raw'], + [IntegrationType.TTN, '/assets/converters/tbel-ttn-tti-encoder.raw'], + [IntegrationType.MQTT, '/assets/converters/tbel-mqtt-encoder.raw'], + [IntegrationType.CHIRPSTACK, '/assets/converters/tbel-chirpstack-encoder.raw'], + [IntegrationType.LORIOT, '/assets/converters/tbel-loriot-encoder.raw'] +]) + +export const IntegrationJSDefaultEncodersUrl = new Map([ + [IntegrationType.TTI, '/assets/converters/js-ttn-tti-encoder.raw'], + [IntegrationType.TTN, '/assets/converters/js-ttn-tti-encoder.raw'], + [IntegrationType.MQTT, '/assets/converters/js-mqtt-encoder.raw'], + [IntegrationType.CHIRPSTACK, '/assets/converters/js-chirpstack-encoder.raw'], + [IntegrationType.LORIOT, '/assets/converters/js-loriot-encoder.raw'] ]) export const jsDefaultConvertersUrl = new Map([ @@ -262,16 +275,19 @@ export const getTargetField = export const getTargetTemplateUrl = (converterType: ConverterType, scriptLang: ScriptLanguage, integrationType: IntegrationType, converterVersion: ConverterVersion = 1): string => { - if (scriptLang === ScriptLanguage.JS && converterType === ConverterType.UPLINK && IntegrationJSDefaultConvertersUrl.has(integrationType)) { - return IntegrationJSDefaultConvertersUrl.get(integrationType) - } else if (scriptLang === ScriptLanguage.JS) { - return getJsTemplateUrl(converterType, converterVersion); - } else if (converterType === ConverterType.UPLINK && IntegrationTbelDefaultConvertersUrl.has(integrationType)) { - return IntegrationTbelDefaultConvertersUrl.get(integrationType); - } else if (converterType === ConverterType.DOWNLINK && IntegrationTbelDefaultEncodersUrl.has(integrationType)) { - return IntegrationTbelDefaultEncodersUrl.get(integrationType); + const isJs = scriptLang === ScriptLanguage.JS; + const isUplink = converterType === ConverterType.UPLINK; + // Integration-specific template map for this (language, direction); UPLINK -> decoders, DOWNLINK -> encoders. + const integrationUrls = isJs + ? (isUplink ? IntegrationJSDefaultDecodersUrl : IntegrationJSDefaultEncodersUrl) + : (isUplink ? IntegrationTbelDefaultDecodersUrl : IntegrationTbelDefaultEncodersUrl); + if (integrationUrls.has(integrationType)) { + return integrationUrls.get(integrationType); } - return getTbelTemplateUrl(converterType, converterVersion); + // Fall back to the generic template for the script language. + return isJs + ? getJsTemplateUrl(converterType, converterVersion) + : getTbelTemplateUrl(converterType, converterVersion); } const getTbelConverterFunctionHeldId = (converterType: ConverterType, converterVersion: ConverterVersion): string => { diff --git a/ui-ngx/src/assets/converters/js-chirpstack-encoder.raw b/ui-ngx/src/assets/converters/js-chirpstack-encoder.raw new file mode 100644 index 0000000000..3e8ec1d4b1 --- /dev/null +++ b/ui-ngx/src/assets/converters/js-chirpstack-encoder.raw @@ -0,0 +1,37 @@ +// Encode downlink data from incoming Rule Engine message + +// msg - JSON message payload downlink message json +// msgType - type of message, for ex. 'ATTRIBUTES_UPDATED', 'POST_TELEMETRY_REQUEST', etc. +// metadata - list of key-value pairs with additional data about the message +// ChirpStack reads DevEUI and fPort from the metadata below to enqueue the downlink (POST .../devices/{DevEUI}/queue). +// Both are client-side device attributes that could be populated via an Originator attributes rule node. +// ThingsBoard prefixes client-scope attributes with "cs_": +// metadata.cs_eui — ChirpStack device EUI stored on first uplink (e.g. "466ECD510CF7B021") +// metadata.cs_fPort — LoRaWAN frame port stored on first uplink (e.g. "1") +// integrationMetadata - list of key-value pairs with additional data defined in Integration executing this converter + +/** Encoder **/ + +// EXAMPLE — replace this: it encodes a single field ('powerState') from the downlink message. +// Swap 'powerState' (and the 'unspecified' fallback) for the field(s) and encoding your device expects; +// as written, any downlink without a 'powerState' field sends the constant value 'unspecified'. +var base64Payload = (msg.powerState != null) + ? btoa(msg.powerState) // if powerState is present, encode it to base64 + : btoa('unspecified'); // fall back to 'unspecified' when absent + +// Result object with encoded downlink payload +var result = { + // downlink data content type: JSON, TEXT or BINARY (base64 format) + contentType: "TEXT", + // downlink data + data: base64Payload, + // Metadata required by ChirpStack for downlink delivery. + metadata: { + // Target device EUI; ChirpStack rejects the downlink if this is missing. + DevEUI: metadata.cs_eui, + // LoRaWAN frame port (1-223); ChirpStack parses this as an integer. + fPort: metadata.cs_fPort + } +}; + +return result; diff --git a/ui-ngx/src/assets/converters/js-loriot-decoder.raw b/ui-ngx/src/assets/converters/js-loriot-decoder.raw index 8021611b56..b0bcab08a2 100644 --- a/ui-ngx/src/assets/converters/js-loriot-decoder.raw +++ b/ui-ngx/src/assets/converters/js-loriot-decoder.raw @@ -52,6 +52,13 @@ function decodePayload(input) { // }; } +// Process only LORIOT uplink messages: cmd is 'rx', or 'gw' when gateway info is included. +// Skip downlink confirmations (e.g. cmd == 'txd') and other events so they +// are not stored as telemetry. Returning an empty array yields no uplink data. +if (metadata.cmd != 'rx' && metadata.cmd != 'gw') { + return []; +} + var result = decodePayload(payload); // Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; // result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. diff --git a/ui-ngx/src/assets/converters/js-loriot-encoder.raw b/ui-ngx/src/assets/converters/js-loriot-encoder.raw new file mode 100644 index 0000000000..879469edec --- /dev/null +++ b/ui-ngx/src/assets/converters/js-loriot-encoder.raw @@ -0,0 +1,37 @@ +// Encode downlink data from incoming Rule Engine message. +// msg - JSON message payload (e.g. { "state": "on" }) +// msgType - message type, e.g. 'ATTRIBUTES_UPDATED' +// metadata - enriched by the Originator attributes node with device client attributes. +// ThingsBoard prefixes client-scope attributes with "cs_": +// metadata.cs_eui — LORIOT device EUI stored on first uplink (e.g. "466ECD510CF7B021") +// metadata.cs_fPort — LoRaWAN frame port stored on first uplink (e.g. "1") + +var eui = metadata.cs_eui; + +// Default port to 1 when the device fPort attribute is missing or empty. +var port = (metadata.cs_fPort != null && metadata.cs_fPort != '') + ? parseInt(metadata.cs_fPort) + : 1; + +// EXAMPLE — replace this: it sends a single field ('powerState') from the downlink message. +// Swap 'powerState' (and the 'unspecified' fallback) for the field your device expects; +// as written, any downlink without a 'powerState' field sends the constant value 'unspecified'. +var payload = (msg.powerState != null) + ? msg.powerState + : 'unspecified'; + +var result = { + // Downlink data content type: JSON, TEXT, or BINARY (base64 format). + contentType: "TEXT", + + // Downlink data — the command value; LORIOT hex-encodes it before delivery. + data: payload, + + // Metadata required by LORIOT for downlink delivery. + metadata: { + "EUI": eui, + "port": port + } +}; + +return result; diff --git a/ui-ngx/src/assets/converters/js-mqtt-encoder.raw b/ui-ngx/src/assets/converters/js-mqtt-encoder.raw new file mode 100644 index 0000000000..71739f2029 --- /dev/null +++ b/ui-ngx/src/assets/converters/js-mqtt-encoder.raw @@ -0,0 +1,20 @@ +// Encode downlink data from incoming Rule Engine message + +// msg - JSON message payload downlink message json +// msgType - type of message, for ex. 'ATTRIBUTES_UPDATED', 'POST_TELEMETRY_REQUEST', etc. +// metadata - list of key-value pairs with additional data about the message +// integrationMetadata - list of key-value pairs with additional data defined in Integration executing this converter + +/** Encoder **/ + +// Publish the ThingsBoard message as JSON to the device upload topic. +// metadata.topic is read by the integration when Downlink topic pattern is ${topic}. +var result = { + contentType: "JSON", + data: JSON.stringify(msg), + metadata: { + topic: metadata['deviceType'] + '/' + metadata['deviceName'] + '/upload' + } +}; + +return result; diff --git a/ui-ngx/src/assets/converters/js-ttn-tti-encoder.raw b/ui-ngx/src/assets/converters/js-ttn-tti-encoder.raw new file mode 100644 index 0000000000..e30c1c75ef --- /dev/null +++ b/ui-ngx/src/assets/converters/js-ttn-tti-encoder.raw @@ -0,0 +1,49 @@ +// Encode downlink data from incoming Rule Engine message +// Shared by the TTN and TTI integrations (The Things Stack). + +// msg - JSON message payload downlink message json +// msgType - type of message, for ex. 'ATTRIBUTES_UPDATED', 'POST_TELEMETRY_REQUEST', etc. +// metadata - list of key-value pairs with additional data about the message +// integrationMetadata - list of key-value pairs with additional data defined in Integration executing this converter + +/** Encoder **/ + +// Target device identifier used to build the TTN/TTI downlink topic (devId is assumed to be added via Originator fields rule node) +var devId = metadata.devId; +// LoRaWAN frame port the downlink is scheduled on (cs_fPort is assumed to be added via Originator attributes rule node, prefix 'cs_' (client-side) is added by rule node) +// Default port to 1 when the device fPort attribute is missing or empty. parseInt keeps f_port a number, as the TTN/TTI API expects. +var fPort = (metadata.cs_fPort != null && metadata.cs_fPort != '') + ? parseInt(metadata.cs_fPort) + : 1; + +// EXAMPLE — replace this: it encodes a single field ('powerState') from the downlink message. +// Swap 'powerState' (and the 'unspecified' fallback) for the field(s) and encoding your device expects; +// as written, any downlink without a 'powerState' field sends the constant value 'unspecified'. +var base64Payload = (msg.powerState != null) + ? btoa(msg.powerState) // if powerState is present, encode it to base64 + : btoa('unspecified'); // fall back to 'unspecified' when absent + +// The Things Stack (TTN/TTI) expects a 'downlinks' array; each entry is a single scheduled downlink. +var data = { + downlinks: [{ + // Frame port to deliver the payload on (must match the device's expected port). + f_port: fPort, + // false - best-effort downlink; set to true to request an acknowledgement from the device. + confirmed: false, + // Downlink payload, base64-encoded as required by the TTN/TTI API. + frm_payload: base64Payload, + // Scheduling priority for the network server: LOWEST, LOW, BELOW_NORMAL, NORMAL, ABOVE_NORMAL, HIGH, HIGHEST. + priority: "NORMAL" + }] +}; + +// Result object with encoded downlink payload +var result = { + contentType: "JSON", + data: JSON.stringify(data), + metadata: { + devId: devId + } +}; + +return result; diff --git a/ui-ngx/src/assets/converters/tbel-chirpstack-encoder.raw b/ui-ngx/src/assets/converters/tbel-chirpstack-encoder.raw new file mode 100644 index 0000000000..3e8ec1d4b1 --- /dev/null +++ b/ui-ngx/src/assets/converters/tbel-chirpstack-encoder.raw @@ -0,0 +1,37 @@ +// Encode downlink data from incoming Rule Engine message + +// msg - JSON message payload downlink message json +// msgType - type of message, for ex. 'ATTRIBUTES_UPDATED', 'POST_TELEMETRY_REQUEST', etc. +// metadata - list of key-value pairs with additional data about the message +// ChirpStack reads DevEUI and fPort from the metadata below to enqueue the downlink (POST .../devices/{DevEUI}/queue). +// Both are client-side device attributes that could be populated via an Originator attributes rule node. +// ThingsBoard prefixes client-scope attributes with "cs_": +// metadata.cs_eui — ChirpStack device EUI stored on first uplink (e.g. "466ECD510CF7B021") +// metadata.cs_fPort — LoRaWAN frame port stored on first uplink (e.g. "1") +// integrationMetadata - list of key-value pairs with additional data defined in Integration executing this converter + +/** Encoder **/ + +// EXAMPLE — replace this: it encodes a single field ('powerState') from the downlink message. +// Swap 'powerState' (and the 'unspecified' fallback) for the field(s) and encoding your device expects; +// as written, any downlink without a 'powerState' field sends the constant value 'unspecified'. +var base64Payload = (msg.powerState != null) + ? btoa(msg.powerState) // if powerState is present, encode it to base64 + : btoa('unspecified'); // fall back to 'unspecified' when absent + +// Result object with encoded downlink payload +var result = { + // downlink data content type: JSON, TEXT or BINARY (base64 format) + contentType: "TEXT", + // downlink data + data: base64Payload, + // Metadata required by ChirpStack for downlink delivery. + metadata: { + // Target device EUI; ChirpStack rejects the downlink if this is missing. + DevEUI: metadata.cs_eui, + // LoRaWAN frame port (1-223); ChirpStack parses this as an integer. + fPort: metadata.cs_fPort + } +}; + +return result; diff --git a/ui-ngx/src/assets/converters/tbel-loriot-decoder.raw b/ui-ngx/src/assets/converters/tbel-loriot-decoder.raw index 5628a2f6c4..248015eb7c 100644 --- a/ui-ngx/src/assets/converters/tbel-loriot-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-loriot-decoder.raw @@ -52,6 +52,13 @@ function decodePayload(input) { // }; } +// Process only LORIOT uplink messages: cmd is 'rx', or 'gw' when gateway info is included. +// Skip downlink confirmations (e.g. cmd == 'txd') and other events so they +// are not stored as telemetry. Returning an empty array yields no uplink data. +if (metadata.cmd != 'rx' && metadata.cmd != 'gw') { + return []; +} + var result = decodePayload(payload); // Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; // result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. diff --git a/ui-ngx/src/assets/converters/tbel-loriot-encoder.raw b/ui-ngx/src/assets/converters/tbel-loriot-encoder.raw new file mode 100644 index 0000000000..879469edec --- /dev/null +++ b/ui-ngx/src/assets/converters/tbel-loriot-encoder.raw @@ -0,0 +1,37 @@ +// Encode downlink data from incoming Rule Engine message. +// msg - JSON message payload (e.g. { "state": "on" }) +// msgType - message type, e.g. 'ATTRIBUTES_UPDATED' +// metadata - enriched by the Originator attributes node with device client attributes. +// ThingsBoard prefixes client-scope attributes with "cs_": +// metadata.cs_eui — LORIOT device EUI stored on first uplink (e.g. "466ECD510CF7B021") +// metadata.cs_fPort — LoRaWAN frame port stored on first uplink (e.g. "1") + +var eui = metadata.cs_eui; + +// Default port to 1 when the device fPort attribute is missing or empty. +var port = (metadata.cs_fPort != null && metadata.cs_fPort != '') + ? parseInt(metadata.cs_fPort) + : 1; + +// EXAMPLE — replace this: it sends a single field ('powerState') from the downlink message. +// Swap 'powerState' (and the 'unspecified' fallback) for the field your device expects; +// as written, any downlink without a 'powerState' field sends the constant value 'unspecified'. +var payload = (msg.powerState != null) + ? msg.powerState + : 'unspecified'; + +var result = { + // Downlink data content type: JSON, TEXT, or BINARY (base64 format). + contentType: "TEXT", + + // Downlink data — the command value; LORIOT hex-encodes it before delivery. + data: payload, + + // Metadata required by LORIOT for downlink delivery. + metadata: { + "EUI": eui, + "port": port + } +}; + +return result; diff --git a/ui-ngx/src/assets/converters/tbel-mqtt-encoder.raw b/ui-ngx/src/assets/converters/tbel-mqtt-encoder.raw new file mode 100644 index 0000000000..71739f2029 --- /dev/null +++ b/ui-ngx/src/assets/converters/tbel-mqtt-encoder.raw @@ -0,0 +1,20 @@ +// Encode downlink data from incoming Rule Engine message + +// msg - JSON message payload downlink message json +// msgType - type of message, for ex. 'ATTRIBUTES_UPDATED', 'POST_TELEMETRY_REQUEST', etc. +// metadata - list of key-value pairs with additional data about the message +// integrationMetadata - list of key-value pairs with additional data defined in Integration executing this converter + +/** Encoder **/ + +// Publish the ThingsBoard message as JSON to the device upload topic. +// metadata.topic is read by the integration when Downlink topic pattern is ${topic}. +var result = { + contentType: "JSON", + data: JSON.stringify(msg), + metadata: { + topic: metadata['deviceType'] + '/' + metadata['deviceName'] + '/upload' + } +}; + +return result; diff --git a/ui-ngx/src/assets/converters/tbel-ttn-tti-encoder.raw b/ui-ngx/src/assets/converters/tbel-ttn-tti-encoder.raw new file mode 100644 index 0000000000..a8306cddab --- /dev/null +++ b/ui-ngx/src/assets/converters/tbel-ttn-tti-encoder.raw @@ -0,0 +1,49 @@ +// Encode downlink data from incoming Rule Engine message +// Shared by the TTN and TTI integrations (The Things Stack). + +// msg - JSON message payload downlink message json +// msgType - type of message, for ex. 'ATTRIBUTES_UPDATED', 'POST_TELEMETRY_REQUEST', etc. +// metadata - list of key-value pairs with additional data about the message +// integrationMetadata - list of key-value pairs with additional data defined in Integration executing this converter + +/** Encoder **/ + +// Target device identifier used to build the TTN/TTI downlink topic (devId is assumed to be added via Originator fields rule node) +var devId = metadata.devId; +// LoRaWAN frame port the downlink is scheduled on (cs_fPort is assumed to be added via Originator attributes rule node, prefix 'cs_' (client-side) is added by rule node) +// Default port to 1 when the device fPort attribute is missing or empty. parseInt keeps f_port a number, as the TTN/TTI API expects. +var fPort = (metadata.cs_fPort != null && metadata.cs_fPort != '') + ? parseInt(metadata.cs_fPort) + : 1; + +// EXAMPLE — replace this: it encodes a single field ('powerState') from the downlink message. +// Swap 'powerState' (and the 'unspecified' fallback) for the field(s) and encoding your device expects; +// as written, any downlink without a 'powerState' field sends the constant value 'unspecified'. +var base64Payload = (msg.powerState != null) + ? btoa(msg.powerState) // if powerState is present, encode it to base64 + : btoa('unspecified'); // fall back to 'unspecified' when absent + +// The Things Stack (TTN/TTI) expects a 'downlinks' array; each entry is a single scheduled downlink. +var data = { + downlinks: [{ + // Frame port to deliver the payload on (must match the device's expected port). + f_port: fPort, + // false - best-effort downlink; set to true to request an acknowledgement from the device. + confirmed: false, + // Downlink payload, base64-encoded as required by the TTN/TTI API. + frm_payload: base64Payload, + // Scheduling priority for the network server: LOWEST, LOW, BELOW_NORMAL, NORMAL, ABOVE_NORMAL, HIGH, HIGHEST. + priority: "NORMAL" + }] +}; + +// Result object with encoded downlink payload +var result = { + contentType: "JSON", + data: JSON.stringify(data), + metadata: { + devId: devId + } +}; + +return result;