diff --git a/TEST_FAST.md b/TEST_FAST.md
index fbea72db9c..11f8969fca 100644
--- a/TEST_FAST.md
+++ b/TEST_FAST.md
@@ -42,10 +42,12 @@ Use `-Dpkg.skip=true` to skip all packaging at once (equivalent to all four flag
|----------------------------|-------------------------------------------|--------------------------------------------------------------|
| `-Dpkg.skip=true` | All of the below (bootjar + deb + rpm + zip) | Yes |
| `-Dpkg.skip.bootjar=true` | `spring-boot:repackage` (`*-boot.jar`) | Yes — tests use the regular `.jar`, not the fat boot jar |
-| `-Dpkg.skip.deb=true` | Gradle `buildDeb` + Maven `attach-artifact` | Yes — MSA docker modules copy the DEB from `target/` directly |
+| `-Dpkg.skip.deb=true` | Gradle `buildDeb` | Yes — MSA docker modules copy the DEB from `target/` directly |
| `-Dpkg.skip.rpm=true` | Gradle `buildRpm` | Yes — no test depends on the RPM |
| `-Dpkg.skip.zip=true` | `maven-assembly-plugin` Windows ZIP | Yes — no test depends on the ZIP |
+`-Dskip.yarn=true` and `-Dskip.ui.build=true` imply `-Dpkg.skip=true`: packages built without the UI are incomplete.
+
## Testcontainers compatibility with the Docker API workaround
In case your tests failed to run testcontainers due to unsupported Docker API version
diff --git a/application/pom.xml b/application/pom.xml
index 6cd1435b2c..6dc44433f9 100644
--- a/application/pom.xml
+++ b/application/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.3.1.6-SNAPSHOT
+ 4.3.1.7-SNAPSHOTthingsboardapplication
diff --git a/application/src/main/data/upgrade/basic/schema_update.sql b/application/src/main/data/upgrade/basic/schema_update.sql
index 20a3528e9a..c7ac2598a0 100644
--- a/application/src/main/data/upgrade/basic/schema_update.sql
+++ b/application/src/main/data/upgrade/basic/schema_update.sql
@@ -3,6 +3,8 @@
-- SPDX-License-Identifier: Apache-2.0
--
+-- Runs before schema-entities.sql and the LTS schema migrations: reference only tables a released version already has.
+
-- UPDATE TENANT PROFILE CONFIGURATION START
UPDATE tenant_profile
diff --git a/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql
new file mode 100644
index 0000000000..740462d6c9
--- /dev/null
+++ b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql
@@ -0,0 +1,29 @@
+--
+-- SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+-- SPDX-License-Identifier: Apache-2.0
+--
+
+-- TB_CLUSTER START
+
+-- The patch path never runs schema-entities.sql, so tb_cluster is created here too.
+-- Keep this block identical to the one in schema-entities.sql.
+
+CREATE TABLE IF NOT EXISTS tb_cluster (
+ cluster_id uuid NOT NULL,
+ license_claim_token varchar,
+ license_secret varchar,
+ CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id)
+);
+
+-- Backstop against two concurrent install jobs both minting an id: a unique index on a constant
+-- expression allows at most one row in the table, no matter how many rows race to insert.
+CREATE UNIQUE INDEX IF NOT EXISTS tb_cluster_single_row ON tb_cluster ((true));
+
+-- TB_CLUSTER END
+
+-- TB_CLUSTER LICENSE SECRET START
+
+-- The CREATE above is a no-op on a database that already carries tb_cluster.
+ALTER TABLE tb_cluster ADD COLUMN IF NOT EXISTS license_secret varchar;
+
+-- TB_CLUSTER LICENSE SECRET END
diff --git a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java
index 533ef331bd..9b85e65762 100644
--- a/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java
+++ b/application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java
@@ -196,8 +196,8 @@ public class TenantActor extends RuleChainManagerActor {
private void forwardToCfActor(TenantAwareMsg msg, boolean priority) {
if (cfActor == null) {
- if (msg instanceof CalculatedFieldStateRestoreMsg) {
- log.warn("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg);
+ if (msg instanceof CalculatedFieldStateRestoreMsg restoreMsg) {
+ log.warn("[{}] CF Actor is not initialized. Skipping CF state restore: [{}]", tenantId, restoreMsg.getId());
} else {
log.debug("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg);
}
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 0eeb602c1d..9e638d271b 100644
--- a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
+++ b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
@@ -75,8 +75,11 @@ public class ThingsboardSecurityConfiguration {
public static final String WS_ENTRY_POINT = "/api/ws/**";
public static final String MAIL_OAUTH2_PROCESSING_ENTRY_POINT = "/api/admin/mail/oauth2/code";
public static final String DEVICE_CONNECTIVITY_CERTIFICATE_DOWNLOAD_ENTRY_POINT = "/api/device-connectivity/*/certificate/download";
+ public static final String COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT = "/api/communityGrant/offline/run";
+ public static final String COMMUNITY_GRANT_OFFLINE_RUN_PAYLOAD_LIMIT = COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT + "=35651584";
- @Value("${server.http.max_payload_size:/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}")
+ // First match wins, so the community grant entry must stay ahead of /api/**.
+ @Value("${server.http.max_payload_size:/api/communityGrant/offline/run=35651584;/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}")
private String maxPayloadSizeConfig;
@Autowired
@@ -133,9 +136,13 @@ public class ThingsboardSecurityConfiguration {
@Autowired
private HttpSecurityHeadersCustomizer httpSecurityHeadersCustomizer;
+ // An override replaces the whole list, so the offline upload's entry is re-added unless it names that path.
@Bean
protected PayloadSizeFilter payloadSizeFilter() {
- return new PayloadSizeFilter(maxPayloadSizeConfig);
+ String config = maxPayloadSizeConfig.contains(COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT + "=")
+ ? maxPayloadSizeConfig
+ : COMMUNITY_GRANT_OFFLINE_RUN_PAYLOAD_LIMIT + ";" + maxPayloadSizeConfig;
+ return new PayloadSizeFilter(config);
}
@Bean
diff --git a/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java
new file mode 100644
index 0000000000..8df6f400ac
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java
@@ -0,0 +1,213 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.controller;
+
+import io.swagger.v3.oas.annotations.Hidden;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestPart;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+import org.thingsboard.server.common.data.audit.ActionType;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo;
+import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
+import org.thingsboard.server.common.data.exception.ThingsboardException;
+import org.thingsboard.server.dao.subscription.TbClusterStore;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+import org.thingsboard.server.service.community_grant.CommunityGrantOfflineBundle;
+import org.thingsboard.server.service.community_grant.CommunityGrantPlatform;
+import org.thingsboard.server.service.community_grant.CommunityGrantService;
+import org.thingsboard.server.service.security.model.SecurityUser;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Optional;
+import java.util.UUID;
+
+@Hidden
+@RestController
+@TbCoreComponent
+@RequestMapping("/api/communityGrant")
+@RequiredArgsConstructor
+@Slf4j
+public class CommunityGrantController extends BaseController {
+
+ private static final String REPORT_FILE_NAME = "tb-instance-check-report.txt";
+
+ @Value("${community-grant.max-checker-size-bytes:33554432}")
+ private long maxCheckerSizeBytes;
+
+ private final CommunityGrantService communityGrantService;
+ private final TbClusterStore tbClusterStore;
+
+ @PreAuthorize("hasAuthority('SYS_ADMIN')")
+ @GetMapping("/state")
+ @ResponseBody
+ public CommunityGrantStateInfo getState() {
+ return communityGrantService.getStateInfo();
+ }
+
+ /** Every failure is audited as a refusal, hence the catch on {@code Exception}. */
+ @PreAuthorize("hasAuthority('SYS_ADMIN')")
+ @PostMapping("/start")
+ @ResponseBody
+ public CommunityGrantStateInfo start() throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ CommunityGrantStateInfo stateInfo;
+ try {
+ stateInfo = communityGrantService.start();
+ } catch (Exception e) {
+ auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(),
+ user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, e);
+ throw e;
+ }
+ auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(),
+ user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, null);
+ return stateInfo;
+ }
+
+ /**
+ * Answers {@code 202} once the run has started on this node; a refusal is audited here, and the run
+ * audits its own ending.
+ */
+ @PreAuthorize("hasAuthority('SYS_ADMIN')")
+ @PostMapping(value = "/offline/run", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ public ResponseEntity runOfflineChecker(@RequestPart("bundle") MultipartFile bundle)
+ throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ CommunityGrantStateInfo stateInfo;
+ try {
+ stateInfo = runOfflineChecker(bundle, user);
+ } catch (Exception e) {
+ auditOfflineRun(user, e);
+ throw e;
+ }
+ return ResponseEntity.status(HttpStatus.ACCEPTED).body(stateInfo);
+ }
+
+ private void auditOfflineRun(SecurityUser user, Exception failure) {
+ auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(),
+ user.getId(), user, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, failure);
+ }
+
+ private CommunityGrantStateInfo runOfflineChecker(MultipartFile bundle, SecurityUser user)
+ throws ThingsboardException {
+ long maxBundleSize = maxCheckerSizeBytes + CommunityGrantOfflineBundle.MAX_OVERHEAD_BYTES;
+ if (bundle.getSize() > maxBundleSize) {
+ throw new ThingsboardException("The uploaded enrollment bundle is larger than the configured limit of "
+ + maxBundleSize + " bytes", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ byte[] bundleData;
+ try {
+ bundleData = bundle.getBytes();
+ } catch (IOException e) {
+ throw new ThingsboardException("Failed to read the uploaded file", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ CommunityGrantOfflineBundle parsed;
+ try {
+ parsed = CommunityGrantOfflineBundle.parse(bundleData);
+ } catch (IllegalArgumentException e) {
+ throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ refuseBundleForAnotherInstallation(parsed);
+ refuseBundleForAnotherPlatform(parsed);
+ warnIfChallengeExpired(parsed, user);
+ return communityGrantService.runOfflineChecker(parsed.checker(), parsed.signature(),
+ parsed.checkerFileName(), parsed.checkerInput(), failure -> auditOfflineRun(user, failure));
+ }
+
+ /** Skipped when this deployment has no cluster id at all. */
+ private void refuseBundleForAnotherInstallation(CommunityGrantOfflineBundle parsed) throws ThingsboardException {
+ Optional clusterId = tbClusterStore.getClusterId();
+ if (clusterId.isPresent() && !clusterId.get().equals(parsed.clusterId())) {
+ throw new ThingsboardException("This enrollment bundle was issued for a different installation. "
+ + "Download a bundle for this installation from the License Portal and upload that one.",
+ ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ }
+
+ private void refuseBundleForAnotherPlatform(CommunityGrantOfflineBundle parsed) throws ThingsboardException {
+ CommunityGrantPlatform platform;
+ try {
+ platform = CommunityGrantPlatform.current();
+ } catch (RuntimeException e) {
+ log.debug("Refusing an enrollment bundle: this server's platform has no instance checker build", e);
+ throw new ThingsboardException("This server's operating system and CPU architecture have no "
+ + "instance checker build, so an enrollment bundle cannot be run here.",
+ ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ if (!platform.os().equals(parsed.os()) || !platform.arch().equals(parsed.arch())) {
+ throw new ThingsboardException("This enrollment bundle is for " + parsed.os() + "/" + parsed.arch()
+ + ", and this server is " + platform.os() + "/" + platform.arch()
+ + ". Download the bundle for this server's platform.", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ }
+
+ /** Warns, never blocks: the portal is the authoritative clock, and an air-gapped host may have drifted. */
+ private void warnIfChallengeExpired(CommunityGrantOfflineBundle parsed, SecurityUser user) {
+ if (parsed.isChallengeExpired(System.currentTimeMillis())) {
+ log.warn("Running an instance checker from an enrollment bundle whose challenge expired at {} "
+ + "(requested by user {}). The portal will refuse the report it produces; a fresh "
+ + "bundle is the remedy.",
+ Instant.ofEpochMilli(parsed.challengeExpiresAt()), user.getId());
+ }
+ }
+
+ @PreAuthorize("hasAuthority('SYS_ADMIN')")
+ @PostMapping("/requestAccess")
+ public void requestAccess() throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ try {
+ communityGrantService.requestAccess();
+ } catch (Exception e) {
+ auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(),
+ user.getId(), user, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, e);
+ throw e;
+ }
+ auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(),
+ user.getId(), user, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, null);
+ }
+
+ @PreAuthorize("hasAuthority('SYS_ADMIN')")
+ @PostMapping("/offline/handoff")
+ @ResponseBody
+ public CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ CommunityGrantStateInfo stateInfo;
+ try {
+ stateInfo = communityGrantService.confirmOfflineHandoff();
+ } catch (Exception e) {
+ auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(),
+ user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, e);
+ throw e;
+ }
+ auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(),
+ user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, null);
+ return stateInfo;
+ }
+
+ @PreAuthorize("hasAuthority('SYS_ADMIN')")
+ @GetMapping("/offline/report")
+ public ResponseEntity downloadOfflineReport() throws ThingsboardException {
+ byte[] report = communityGrantService.getOfflineReport().getBytes(StandardCharsets.UTF_8);
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + REPORT_FILE_NAME + "\"")
+ .contentType(MediaType.TEXT_PLAIN)
+ .contentLength(report.length)
+ .body(new ByteArrayResource(report));
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
index ffa76d658a..b582612803 100644
--- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
+++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
@@ -12,6 +12,7 @@ import jakarta.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@@ -35,6 +36,7 @@ import org.thingsboard.server.common.data.rpc.RpcStatus;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg;
+import org.thingsboard.server.service.rpc.TbRpcService;
import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.exception.ToErrorResponseEntity;
import org.thingsboard.server.queue.util.TbCoreComponent;
@@ -62,6 +64,9 @@ import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CU
@Slf4j
public class RpcV2Controller extends AbstractRpcController {
+ @Autowired
+ private TbRpcService tbRpcService;
+
private static final String RPC_REQUEST_DESCRIPTION = "Sends the one-way remote-procedure call (RPC) request to device. " +
"The RPC call is A JSON that contains the method name ('method'), parameters ('params') and multiple optional fields. " +
"See example below. We will review the properties of the RPC call one-by-one below. " +
@@ -220,13 +225,13 @@ public class RpcV2Controller extends AbstractRpcController {
Rpc rpc = checkRpcId(rpcId, Operation.DELETE);
if (rpc != null) {
- if (rpc.getStatus().isPushDeleteNotificationToCore()) {
+ if (rpc.getStatus().isIntermediate()) {
RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId());
log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc);
tbClusterService.pushMsgToCore(removeMsg, null);
}
- rpcService.deleteRpc(getTenantId(), rpcId);
+ tbRpcService.deleteRpc(getTenantId(), rpc);
rpc.setStatus(RpcStatus.DELETED);
TbMsg msg = TbMsg.newMsg()
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 a7e3ed4ba9..2e8dda4d32 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
@@ -19,6 +19,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 +35,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;
@@ -55,6 +57,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;
@@ -76,6 +79,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<>();
@@ -181,7 +186,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke
log.trace("{} Authenticating session", sessionRef);
SecurityUser securityCtx;
try {
- securityCtx = authenticationProvider.authenticate(authCmd.getToken());
+ securityCtx = authenticate(authCmd.getToken());
} catch (Exception e) {
close(sessionRef, CloseStatus.BAD_DATA.withReason(e.getMessage()));
return;
@@ -317,7 +322,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke
SecurityUser securityCtx = null;
String token = StringUtils.substringAfter(session.getUri().getQuery(), "token=");
if (StringUtils.isNotEmpty(token)) {
- securityCtx = authenticationProvider.authenticate(token);
+ securityCtx = authenticate(token);
}
return WebSocketSessionRef.builder()
.sessionId(UUID.randomUUID().toString())
@@ -328,6 +333,14 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke
.build();
}
+ 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 0f2c37a8dc..508edc321b 100644
--- a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
+++ b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
@@ -112,6 +112,7 @@ public class ThingsboardInstallService {
systemDataLoaderService.loadSystemWidgets();
installScripts.loadSystemLwm2mResources();
installScripts.loadSystemImagesAndResources();
+ entityDatabaseSchemaService.generateClusterIdIfNotExist();
databaseSchemaVersionService.updateSchemaVersion();
}
log.info("Upgrade finished successfully!");
@@ -158,6 +159,8 @@ public class ThingsboardInstallService {
installScripts.loadSystemLwm2mResources();
installScripts.loadSystemImagesAndResources();
+ entityDatabaseSchemaService.generateClusterIdIfNotExist();
+
if (loadDemo) {
log.info("Loading demo data...");
systemDataLoaderService.loadDemoData();
diff --git a/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java b/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java
index e4850b9128..72f34918c8 100644
--- a/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java
+++ b/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java
@@ -70,6 +70,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -489,10 +490,17 @@ public abstract class AbstractCalculatedFieldProcessingService {
callback.onFailure(new IllegalArgumentException("Only TimeSeriesImmediateOutputStrategy is supported."));
} else {
TimeseriesSaveRequest.Strategy strategy = new TimeseriesSaveRequest.Strategy(tsOutputStrategy.isSaveTimeSeries(), tsOutputStrategy.isSaveLatest(), tsOutputStrategy.isSendWsUpdate(), tsOutputStrategy.isProcessCfs());
- saveTimeSeriesInternal(tenantId, entityId, jsonResult, tsOutputStrategy.getTtl(), cfIds, ts, strategy, callback);
+ saveTimeSeriesInternal(tenantId, entityId, jsonResult, resolveTtl(tenantId, tsOutputStrategy.getTtl()), cfIds, ts, strategy, callback);
}
}
+ private long resolveTtl(TenantId tenantId, long ttl) {
+ if (ttl == 0L) {
+ return TimeUnit.DAYS.toSeconds(apiLimitService.getLimit(tenantId, DefaultTenantProfileConfiguration::getDefaultStorageTtlDays));
+ }
+ return ttl;
+ }
+
private void saveTimeSeriesInternal(TenantId tenantId, EntityId entityId, JsonElement jsonResult, Long ttl, List cfIds, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) {
Map> tsKvMap = JsonConverter.convertToTelemetry(jsonResult, ts);
if (tsKvMap.isEmpty()) {
diff --git a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java
index 097a0da2f0..f984b23d87 100644
--- a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java
+++ b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java
@@ -4,6 +4,8 @@ package org.thingsboard.server.service.cf.ctx.state.alarm;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.KvUtil;
@@ -38,6 +40,8 @@ public class AlarmRuleState {
private final AlarmSeverity severity;
private AlarmRule alarmRule;
+ @ToString.Exclude
+ @EqualsAndHashCode.Exclude
private AlarmCalculatedFieldState state;
private AlarmCondition condition;
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java
new file mode 100644
index 0000000000..66fa1e6197
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java
@@ -0,0 +1,34 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import lombok.Getter;
+
+/**
+ * Why {@link CommunityGrantOfflineBundle#parse} refused a {@code TBICBDL1} file. The message is shown to the
+ * uploader and stored in an audit row, so it must never carry secrets or the uploaded bytes.
+ */
+@Getter
+public class CommunityGrantBundleFormatException extends IllegalArgumentException {
+
+ /** In the order the checks are made. */
+ public enum Reason {
+ TOO_SHORT,
+ BAD_MAGIC,
+ UNSUPPORTED_VERSION,
+ MANIFEST_LEN_RANGE,
+ CHECKER_LEN_RANGE,
+ LENGTH_MISMATCH,
+ MANIFEST_NOT_UTF8,
+ MANIFEST_NOT_JSON,
+ MANIFEST_FIELD
+ }
+
+ private final Reason reason;
+
+ public CommunityGrantBundleFormatException(Reason reason, String message) {
+ super(message);
+ this.reason = reason;
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java
new file mode 100644
index 0000000000..775ed7b090
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java
@@ -0,0 +1,23 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.thingsboard.common.util.JacksonUtil;
+
+import java.util.Optional;
+
+/**
+ * The portal-decided input for the instance checker, passed through to its {@code TB_IC_INPUT} unread.
+ */
+public record CommunityGrantCheckerInput(String json) {
+
+ /** Empty unless {@code input} is a non-empty JSON object. */
+ public static Optional from(JsonNode input) {
+ if (input == null || !input.isObject() || input.isEmpty()) {
+ return Optional.empty();
+ }
+ return Optional.of(new CommunityGrantCheckerInput(JacksonUtil.toString(input)));
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java
new file mode 100644
index 0000000000..b26e39fbcf
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java
@@ -0,0 +1,17 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import org.springframework.web.client.RestClientException;
+
+/**
+ * Thrown by {@link CommunityGrantPortalClient#downloadChecker} when the checker exceeds the configured size
+ * cap, whether advertised by Content-Length or discovered mid-stream.
+ */
+public class CommunityGrantCheckerTooLargeException extends RestClientException {
+
+ public CommunityGrantCheckerTooLargeException(String message) {
+ super(message);
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java
new file mode 100644
index 0000000000..f40cd9d2de
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java
@@ -0,0 +1,9 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public record CommunityGrantClusterStatus(boolean alreadyRegistered) {
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java
new file mode 100644
index 0000000000..a0be2548f7
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java
@@ -0,0 +1,122 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.common.data.AdminSettings;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantMode;
+import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.dao.settings.AdminSettingsService;
+import org.thingsboard.server.exception.DataValidationException;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.UnaryOperator;
+
+/**
+ * Every write goes through {@link #update}, which re-reads under a per-node lock. {@code admin_settings} has no
+ * unique index on {@code (tenant_id, key)}, so two creates that both commit leave duplicate rows, and every
+ * later read throws until one is deleted by hand.
+ */
+@Component
+@TbCoreComponent
+@RequiredArgsConstructor
+@Slf4j
+public class CommunityGrantFlowStateStore {
+
+ public static final String SETTINGS_KEY = "communityGrant";
+
+ private final AdminSettingsService adminSettingsService;
+
+ private final ReentrantLock updateLock = new ReentrantLock();
+
+ public CommunityGrantFlowState get() {
+ try {
+ return readOrThrow();
+ } catch (IllegalStateException e) {
+ // Read-only fallback; a store failure still propagates.
+ log.warn("Failed to parse the stored community grant flow state, falling back to the initial state", e);
+ return CommunityGrantFlowState.initial();
+ }
+ }
+
+ /**
+ * The updater runs a second time against the winner's document when a create race is lost, so it must be
+ * deterministic: read the clock before the call, not inside it.
+ */
+ public CommunityGrantFlowState update(UnaryOperator updater) {
+ updateLock.lock();
+ try {
+ AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY);
+ JsonNode stored = settings != null ? settings.getJsonValue() : null;
+ CommunityGrantFlowState updated = updater.apply(parseOrThrow(settings));
+ JsonNode serialized = JacksonUtil.valueToTree(updated);
+ // Every poll runs an updater; an unchanged document is not written back.
+ if (serialized.equals(stored)) {
+ return updated;
+ }
+ if (settings == null) {
+ settings = new AdminSettings();
+ settings.setTenantId(TenantId.SYS_TENANT_ID);
+ settings.setKey(SETTINGS_KEY);
+ }
+ settings.setJsonValue(serialized);
+ try {
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings);
+ return updated;
+ } catch (DataValidationException e) {
+ if (settings.getId() != null) {
+ throw e;
+ }
+ // Lost a create race to another node: re-apply the change to the winner's row.
+ AdminSettings winner = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY);
+ if (winner == null) {
+ throw e;
+ }
+ CommunityGrantFlowState reapplied;
+ try {
+ reapplied = updater.apply(parseOrThrow(winner));
+ } catch (RuntimeException retryFailure) {
+ retryFailure.addSuppressed(e);
+ throw retryFailure;
+ }
+ winner.setJsonValue(JacksonUtil.valueToTree(reapplied));
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, winner);
+ return reapplied;
+ }
+ } finally {
+ updateLock.unlock();
+ }
+ }
+
+ private CommunityGrantFlowState readOrThrow() {
+ return parseOrThrow(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY));
+ }
+
+ private CommunityGrantFlowState parseOrThrow(AdminSettings settings) {
+ if (settings == null || settings.getJsonValue() == null || settings.getJsonValue().isNull()) {
+ return CommunityGrantFlowState.initial();
+ }
+ CommunityGrantFlowState flowState;
+ try {
+ flowState = JacksonUtil.treeToValue(settings.getJsonValue(), CommunityGrantFlowState.class);
+ } catch (Exception e) {
+ // The cause is dropped: it carries the whole stored document, claim token included.
+ throw new IllegalStateException("Stored community grant flow state at admin_settings[" + SETTINGS_KEY
+ + "] could not be parsed: " + e.getClass().getSimpleName());
+ }
+ if (flowState == null || flowState.getState() == null) {
+ return CommunityGrantFlowState.initial();
+ }
+ if (flowState.getMode() == null) {
+ flowState.setMode(CommunityGrantMode.ONLINE);
+ }
+ return flowState;
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java
new file mode 100644
index 0000000000..608adff2dc
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java
@@ -0,0 +1,77 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * Rewrites this deployment's JDBC url as the libpq connection string the instance checker's driver
+ * understands.
+ */
+final class CommunityGrantLibpqDsn {
+
+ private static final String JDBC_PREFIX = "jdbc:";
+ private static final String JDBC_POSTGRESQL_PREFIX = "jdbc:postgresql:";
+ private static final String POSTGRES_SCHEME = "postgres://";
+
+ private CommunityGrantLibpqDsn() {
+ }
+
+ /**
+ * The JDBC query string is dropped: its parameters are the JDBC driver's, not libpq's.
+ *
+ * @throws IllegalStateException if the url is not a PostgreSQL JDBC url naming a single host and a
+ * database, or the username is blank
+ */
+ static String from(String jdbcUrl, String username, String password) {
+ if (jdbcUrl == null || !jdbcUrl.startsWith(JDBC_POSTGRESQL_PREFIX)) {
+ throw new IllegalStateException("The datasource url is not a PostgreSQL JDBC url");
+ }
+ URI jdbc;
+ try {
+ jdbc = new URI(jdbcUrl.substring(JDBC_PREFIX.length()));
+ } catch (URISyntaxException e) {
+ // The cause is dropped: its message quotes the url, which may carry the database password.
+ throw new IllegalStateException("The datasource url is not a valid PostgreSQL JDBC url");
+ }
+ if (jdbc.getHost() == null) {
+ throw new IllegalStateException("The datasource url does not name a single host");
+ }
+ String path = jdbc.getPath();
+ if (path == null || path.length() <= 1) {
+ throw new IllegalStateException("The datasource url does not name a database");
+ }
+ if (username == null || username.isBlank()) {
+ throw new IllegalStateException("The datasource has no configured username");
+ }
+ String userInfo = percentEncodeUserInfoComponent(username) + ":"
+ + percentEncodeUserInfoComponent(password == null ? "" : password);
+ try {
+ // Spliced in rather than passed to the URI constructor, which would escape every '%' above again.
+ String withoutUserInfo = new URI("postgres", null, jdbc.getHost(), jdbc.getPort(), path, null, null)
+ .toASCIIString();
+ return POSTGRES_SCHEME + userInfo + "@" + withoutUserInfo.substring(POSTGRES_SCHEME.length());
+ } catch (URISyntaxException e) {
+ // The cause is dropped for the same reason as above.
+ throw new IllegalStateException("Failed to build the instance check connection string");
+ }
+ }
+
+ /** Escapes everything outside the RFC 3986 unreserved set, ':' and '%' included. */
+ private static String percentEncodeUserInfoComponent(String value) {
+ StringBuilder encoded = new StringBuilder();
+ for (byte b : value.getBytes(StandardCharsets.UTF_8)) {
+ int c = b & 0xFF;
+ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
+ || c == '-' || c == '.' || c == '_' || c == '~') {
+ encoded.append((char) c);
+ } else {
+ encoded.append('%').append(String.format("%02X", c));
+ }
+ }
+ return encoded.toString();
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java
new file mode 100644
index 0000000000..57c68a9fc4
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java
@@ -0,0 +1,18 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import org.springframework.web.client.HttpStatusCodeException;
+import org.springframework.web.client.RestClientException;
+
+/**
+ * Thrown by {@link CommunityGrantPortalClient#claimLicense} when the portal will not hand the license key
+ * over. Terminal, unlike a transport failure: retrying the claim cannot change the answer.
+ */
+public class CommunityGrantLicenseClaimRefusedException extends RestClientException {
+
+ public CommunityGrantLicenseClaimRefusedException(HttpStatusCodeException cause) {
+ super(cause.getMessage(), cause);
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java
new file mode 100644
index 0000000000..080bc59393
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+public record CommunityGrantLicenseClaimRequest(String claimToken) {
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java
new file mode 100644
index 0000000000..77a6ff114b
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java
@@ -0,0 +1,10 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/** {@code secret} is set only once {@code activated} is true. */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public record CommunityGrantLicenseClaimResponse(boolean activated, String secret) {
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java
new file mode 100644
index 0000000000..09d261e7ae
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java
@@ -0,0 +1,314 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+import org.thingsboard.server.service.community_grant.CommunityGrantBundleFormatException.Reason;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Deque;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+/**
+ * The {@code TBICBDL1} offline enrollment bundle.
+ *
+ * offset width field value / constraint
+ * 0 8 MAGIC "TBICBDL1"
+ * 8 1 VERSION 0x01
+ * 9 4 MANIFEST_LEN uint32 big-endian, 1..8192
+ * 13 4 CHECKER_LEN uint32 big-endian, >= 1
+ * 17 74 RELSIG a complete TBICSIG1 file, verbatim
+ * 91 M MANIFEST UTF-8 JSON
+ * 91+M C CHECKER the executable image
+ *
+ * {@code RELSIG} is not inspected here; {@link CommunityGrantReleaseSignatureVerifier} does that.
+ */
+public record CommunityGrantOfflineBundle(String os, String arch, UUID clusterId, String checkerFileName,
+ long issuedAt, long challengeExpiresAt,
+ CommunityGrantCheckerInput checkerInput, byte[] signature, byte[] checker) {
+
+ public static final int HEADER_LEN = 91;
+ public static final int MIN_MANIFEST_LEN = 1;
+ public static final int MAX_MANIFEST_LEN = 8192;
+
+ public static final int MAX_OVERHEAD_BYTES = HEADER_LEN + MAX_MANIFEST_LEN;
+
+ private static final byte[] MAGIC = {'T', 'B', 'I', 'C', 'B', 'D', 'L', '1'};
+ private static final byte VERSION_V1 = 0x01;
+ private static final int RELSIG_OFFSET = 17;
+ private static final int RELSIG_LEN = 74;
+ private static final long MIN_CHECKER_LEN = 1;
+
+ private static final int MANIFEST_LEN_OFFSET = 9;
+ private static final int CHECKER_LEN_OFFSET = 13;
+
+ private static final int MAX_CHECKER_FILE_NAME_LEN = 255;
+ private static final int MAX_QUOTED_KEY_LEN = 64;
+
+ private static final List KNOWN_OS = List.of("linux", "darwin", "windows");
+ private static final List KNOWN_ARCH = List.of("amd64", "arm64");
+
+ /** {@link UUID#fromString} alone is far too lenient. */
+ private static final Pattern CANONICAL_UUID =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+
+ /** Duplicate keys and trailing content are rejected: parsers disagree on which duplicate wins. */
+ private static final ObjectMapper MANIFEST_MAPPER = JsonMapper.builder()
+ .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+
+ /**
+ * @throws CommunityGrantBundleFormatException with a message safe to show the uploader and to store in
+ * an audit row.
+ */
+ public static CommunityGrantOfflineBundle parse(byte[] data) {
+ int total = data == null ? 0 : data.length;
+ if (total < HEADER_LEN) {
+ throw new CommunityGrantBundleFormatException(Reason.TOO_SHORT, "The uploaded file is " + total
+ + " bytes, shorter than the " + HEADER_LEN + "-byte enrollment bundle header, so it is not"
+ + " a ThingsBoard enrollment bundle.");
+ }
+ if (!Arrays.equals(data, 0, MAGIC.length, MAGIC, 0, MAGIC.length)) {
+ throw new CommunityGrantBundleFormatException(Reason.BAD_MAGIC, "The uploaded file is not a"
+ + " ThingsBoard enrollment bundle: it does not carry the marker every bundle begins with.");
+ }
+ if (data[MAGIC.length] != VERSION_V1) {
+ throw new CommunityGrantBundleFormatException(Reason.UNSUPPORTED_VERSION, "The enrollment bundle"
+ + " declares format version " + (data[MAGIC.length] & 0xFF) + ", and this deployment"
+ + " supports version " + VERSION_V1 + " only.");
+ }
+ // Unsigned: read into a long so 0xFFFFFFFF cannot wrap the length arithmetic.
+ long manifestLen = readUnsignedInt(data, MANIFEST_LEN_OFFSET);
+ long checkerLen = readUnsignedInt(data, CHECKER_LEN_OFFSET);
+ if (manifestLen < MIN_MANIFEST_LEN || manifestLen > MAX_MANIFEST_LEN) {
+ throw new CommunityGrantBundleFormatException(Reason.MANIFEST_LEN_RANGE, "The enrollment bundle"
+ + " declares a manifest of " + manifestLen + " bytes, outside the permitted range of "
+ + MIN_MANIFEST_LEN + " to " + MAX_MANIFEST_LEN + " bytes, so the file is damaged.");
+ }
+ if (checkerLen < MIN_CHECKER_LEN) {
+ throw new CommunityGrantBundleFormatException(Reason.CHECKER_LEN_RANGE, "The enrollment bundle"
+ + " declares a checker of " + checkerLen + " bytes, so the file is damaged.");
+ }
+ long expectedTotal = HEADER_LEN + manifestLen + checkerLen;
+ if (expectedTotal != total) {
+ throw new CommunityGrantBundleFormatException(Reason.LENGTH_MISMATCH, "The enrollment bundle is"
+ + " damaged or truncated: its declared " + manifestLen + "-byte manifest and "
+ + checkerLen + "-byte checker need a file of " + expectedTotal + " bytes, but the"
+ + " uploaded file is " + total + " bytes. Download the bundle again.");
+ }
+ JsonNode manifest = readManifest(data, (int) manifestLen);
+ return new CommunityGrantOfflineBundle(
+ readEnum(manifest, "os", KNOWN_OS),
+ readEnum(manifest, "arch", KNOWN_ARCH),
+ readClusterId(manifest),
+ readCheckerFileName(manifest),
+ readIssuedAt(manifest),
+ readTimestamp(manifest, "challengeExpiresAt"),
+ readCheckerInput(manifest),
+ Arrays.copyOfRange(data, RELSIG_OFFSET, RELSIG_OFFSET + RELSIG_LEN),
+ Arrays.copyOfRange(data, HEADER_LEN + (int) manifestLen, total));
+ }
+
+ /** Strictly later: the portal still accepts the deadline instant itself. */
+ public boolean isChallengeExpired(long now) {
+ return now > challengeExpiresAt;
+ }
+
+ private static long readUnsignedInt(byte[] data, int offset) {
+ return ((long) (data[offset] & 0xFF) << 24)
+ | ((long) (data[offset + 1] & 0xFF) << 16)
+ | ((long) (data[offset + 2] & 0xFF) << 8)
+ | (data[offset + 3] & 0xFF);
+ }
+
+ /** A strict decoder: a substituting one would report binary garbage as bad JSON rather than bad text. */
+ private static JsonNode readManifest(byte[] data, int manifestLen) {
+ CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT);
+ CharBuffer text;
+ try {
+ text = decoder.decode(ByteBuffer.wrap(data, HEADER_LEN, manifestLen));
+ } catch (CharacterCodingException e) {
+ throw new CommunityGrantBundleFormatException(Reason.MANIFEST_NOT_UTF8, "The enrollment bundle's"
+ + " manifest is not readable text, so the file is damaged. Download the bundle again.");
+ }
+ String manifestJson = text.toString();
+ JsonNode manifest;
+ try {
+ manifest = MANIFEST_MAPPER.readTree(manifestJson);
+ } catch (JsonParseException e) {
+ throw notAJsonObject();
+ } catch (IOException e) {
+ // Not a syntax error, so the duplicate-key refusal; Jackson's message does not name the key reliably.
+ String duplicate = findDuplicateKey(manifestJson);
+ if (duplicate == null) {
+ throw notAJsonObject();
+ }
+ throw fieldError(quoteKey(duplicate), "appears more than once");
+ }
+ if (manifest == null || !manifest.isObject()) {
+ throw notAJsonObject();
+ }
+ int declaredVersion = readInt(manifest, "bundleVersion");
+ if (declaredVersion != VERSION_V1) {
+ throw fieldError("bundleVersion", "must be " + VERSION_V1);
+ }
+ return manifest;
+ }
+
+ /** Scans the root value only, so trailing junk is not blamed for a duplicate key. */
+ private static String findDuplicateKey(String manifestJson) {
+ Deque> seenPerObject = new ArrayDeque<>();
+ try (JsonParser parser = MANIFEST_MAPPER.createParser(manifestJson)) {
+ for (JsonToken token = parser.nextToken(); token != null; token = parser.nextToken()) {
+ if (token == JsonToken.START_OBJECT) {
+ seenPerObject.push(new HashSet<>());
+ } else if (token == JsonToken.END_OBJECT) {
+ seenPerObject.pop();
+ if (seenPerObject.isEmpty()) {
+ break;
+ }
+ } else if (token == JsonToken.FIELD_NAME && !seenPerObject.peek().add(parser.currentName())) {
+ return parser.currentName();
+ }
+ }
+ } catch (IOException e) {
+ return null;
+ }
+ return null;
+ }
+
+ private static CommunityGrantBundleFormatException notAJsonObject() {
+ return new CommunityGrantBundleFormatException(Reason.MANIFEST_NOT_JSON, "The enrollment bundle's"
+ + " manifest is not a JSON object, so the file is damaged. Download the bundle again.");
+ }
+
+ /** Never quotes the offending value: the message is shown to the uploader and audited. */
+ private static CommunityGrantBundleFormatException fieldError(String key, String problem) {
+ return new CommunityGrantBundleFormatException(Reason.MANIFEST_FIELD, "The enrollment bundle's"
+ + " manifest is not usable: \"" + key + "\" " + problem + ". Download the bundle again.");
+ }
+
+ /** The one uploaded string a refusal quotes, so it is bounded and stripped of control characters. */
+ private static String quoteKey(String key) {
+ String quoted = key;
+ if (quoted.length() > MAX_QUOTED_KEY_LEN) {
+ // Never cut between the halves of a surrogate pair.
+ int end = Character.isHighSurrogate(quoted.charAt(MAX_QUOTED_KEY_LEN - 1))
+ ? MAX_QUOTED_KEY_LEN - 1 : MAX_QUOTED_KEY_LEN;
+ quoted = quoted.substring(0, end) + "...";
+ }
+ return quoted.replaceAll("\\p{Cntrl}", "?");
+ }
+
+ private static JsonNode required(JsonNode manifest, String key) {
+ JsonNode value = manifest.get(key);
+ if (value == null || value.isNull()) {
+ throw fieldError(key, "is missing");
+ }
+ return value;
+ }
+
+ private static String readString(JsonNode manifest, String key) {
+ JsonNode value = required(manifest, key);
+ if (!value.isTextual()) {
+ throw fieldError(key, "must be a string");
+ }
+ return value.textValue();
+ }
+
+ private static int readInt(JsonNode manifest, String key) {
+ JsonNode value = required(manifest, key);
+ if (!value.isIntegralNumber() || !value.canConvertToInt()) {
+ throw fieldError(key, "must be a whole number");
+ }
+ return value.intValue();
+ }
+
+ private static long readTimestamp(JsonNode manifest, String key) {
+ JsonNode value = required(manifest, key);
+ if (!value.isIntegralNumber() || !value.canConvertToLong()) {
+ throw fieldError(key, "must be a whole number of milliseconds");
+ }
+ long millis = value.longValue();
+ if (millis <= 0) {
+ throw fieldError(key, "must be a positive number of milliseconds");
+ }
+ return millis;
+ }
+
+ private static String readEnum(JsonNode manifest, String key, List permitted) {
+ String value = readString(manifest, key);
+ if (!permitted.contains(value)) {
+ throw fieldError(key, "must be one of " + String.join(", ", permitted));
+ }
+ return value;
+ }
+
+ private static UUID readClusterId(JsonNode manifest) {
+ String value = readString(manifest, "clusterId");
+ if (!CANONICAL_UUID.matcher(value).matches()) {
+ throw fieldError("clusterId", "must be a canonical lowercase UUID");
+ }
+ return UUID.fromString(value);
+ }
+
+ private static String readCheckerFileName(JsonNode manifest) {
+ String value = readString(manifest, "checkerFileName");
+ if (value.isEmpty() || value.length() > MAX_CHECKER_FILE_NAME_LEN) {
+ throw fieldError("checkerFileName", "must be between 1 and " + MAX_CHECKER_FILE_NAME_LEN
+ + " characters");
+ }
+ // Logged verbatim, so control characters could forge log lines.
+ if (value.indexOf('/') >= 0 || value.indexOf('\\') >= 0 || value.contains("..")
+ || containsControlCharacter(value)) {
+ throw fieldError("checkerFileName",
+ "must not contain a path separator, \"..\" or a control character");
+ }
+ return value;
+ }
+
+ private static boolean containsControlCharacter(String value) {
+ for (int i = 0; i < value.length(); i++) {
+ char c = value.charAt(i);
+ if (c < 0x20 || c == 0x7F) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static long readIssuedAt(JsonNode manifest) {
+ long issuedAt = readTimestamp(manifest, "issuedAt");
+ if (issuedAt > readTimestamp(manifest, "challengeExpiresAt")) {
+ throw fieldError("issuedAt", "must not be later than the challenge's expiry");
+ }
+ return issuedAt;
+ }
+
+ private static CommunityGrantCheckerInput readCheckerInput(JsonNode manifest) {
+ return CommunityGrantCheckerInput.from(manifest.get("checkerInput"))
+ .orElseThrow(() -> fieldError("checkerInput", "must be a non-empty object"));
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java
new file mode 100644
index 0000000000..3909e60c21
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java
@@ -0,0 +1,155 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import lombok.AccessLevel;
+import lombok.RequiredArgsConstructor;
+import lombok.Setter;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.common.data.AdminSettings;
+import org.thingsboard.server.common.data.StringUtils;
+import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.dao.settings.AdminSettingsService;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.LongSupplier;
+
+/**
+ * The last offline report: a durable row plus a node-local copy that outranks it until a newer write lands, so
+ * a node whose durable write failed still serves what it produced. Ordering relies on wall clocks across
+ * nodes. {@link #clear()} writes a tombstone so "cleared" differs from "never stored".
+ */
+@Component
+@TbCoreComponent
+@RequiredArgsConstructor
+@Slf4j
+public class CommunityGrantOfflineReportStore {
+
+ public static final String SETTINGS_KEY = "communityGrantReport";
+ private static final String REPORT_FIELD = "report";
+ private static final String UPDATED_AT_FIELD = "updatedAt";
+
+ private final AdminSettingsService adminSettingsService;
+
+ private final AtomicReference nodeLocalReport = new AtomicReference<>();
+
+ @Setter(AccessLevel.PACKAGE)
+ private LongSupplier clock = System::currentTimeMillis;
+
+ /**
+ * The last report, or empty when there is none. A failed read propagates unless this node has a copy of
+ * its own to answer with: a read that did not reach the database is no evidence of absence.
+ */
+ public Optional get() {
+ LocalReport localReport = nodeLocalReport.get();
+ Optional local = Optional.ofNullable(localReport)
+ .map(LocalReport::report)
+ .filter(StringUtils::isNotEmpty);
+ StoredReport stored;
+ try {
+ stored = readStored();
+ } catch (RuntimeException e) {
+ if (localReport == null) {
+ throw e;
+ }
+ log.warn("Failed to read the stored community grant offline report; "
+ + "serving what this node last did itself", e);
+ return local;
+ }
+ if (stored == null) {
+ return local;
+ }
+ if (localReport != null && !localReport.durable()
+ && stored.updatedAt() <= localReport.writtenAt()) {
+ return local;
+ }
+ if (stored.report() == null) {
+ nodeLocalReport.compareAndSet(localReport, null);
+ return Optional.empty();
+ }
+ if (localReport != null && !localReport.durable()) {
+ // Dropped so a later write carrying an earlier instant cannot revive it.
+ nodeLocalReport.compareAndSet(localReport, null);
+ }
+ return Optional.of(stored.report());
+ }
+
+ public void put(String report) {
+ long writtenAt = clock.getAsLong();
+ LocalReport pending = new LocalReport(report, false, writtenAt);
+ nodeLocalReport.set(pending);
+ if (writeStored(report, writtenAt)) {
+ nodeLocalReport.compareAndSet(pending, new LocalReport(report, true, writtenAt));
+ }
+ }
+
+ /**
+ * Retires the report along with the enrollment it belonged to. Until the durable write lands, the local
+ * copy answers empty on this node.
+ */
+ public void clear() {
+ long writtenAt = clock.getAsLong();
+ LocalReport pending = new LocalReport(null, false, writtenAt);
+ nodeLocalReport.set(pending);
+ if (writeStored(null, writtenAt)) {
+ nodeLocalReport.compareAndSet(pending, null);
+ }
+ }
+
+ /** {@code null} for no usable row; a {@link StoredReport} with a {@code null} report for the tombstone. */
+ private StoredReport readStored() {
+ AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY);
+ if (settings == null || settings.getJsonValue() == null) {
+ return null;
+ }
+ JsonNode value = settings.getJsonValue();
+ JsonNode report = value.get(REPORT_FIELD);
+ if (report == null) {
+ return null;
+ }
+ long updatedAt = value.path(UPDATED_AT_FIELD).asLong();
+ if (report.isNull()) {
+ return new StoredReport(null, updatedAt);
+ }
+ return report.isTextual() && !report.asText().isEmpty()
+ ? new StoredReport(report.asText(), updatedAt)
+ : null;
+ }
+
+ /** A null report writes the tombstone. Returns whether the write reached the database. */
+ private boolean writeStored(String report, long updatedAt) {
+ try {
+ AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY);
+ if (settings == null) {
+ settings = new AdminSettings();
+ settings.setTenantId(TenantId.SYS_TENANT_ID);
+ settings.setKey(SETTINGS_KEY);
+ }
+ ObjectNode value = JacksonUtil.newObjectNode();
+ if (report == null) {
+ value.putNull(REPORT_FIELD);
+ } else {
+ value.put(REPORT_FIELD, report);
+ }
+ value.put(UPDATED_AT_FIELD, updatedAt);
+ settings.setJsonValue(value);
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings);
+ return true;
+ } catch (RuntimeException e) {
+ log.warn("Failed to store the community grant offline report", e);
+ return false;
+ }
+ }
+
+ /** A {@code null} report stands for a {@link #clear()}. */
+ private record LocalReport(String report, boolean durable, long writtenAt) {}
+
+ private record StoredReport(String report, long updatedAt) {}
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java
new file mode 100644
index 0000000000..7858638b8c
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java
@@ -0,0 +1,61 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import org.thingsboard.server.common.data.StringUtils;
+
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * The host platform in the vocabulary the portal's {@code /checker} endpoint expects.
+ */
+public record CommunityGrantPlatform(String os, String arch) {
+
+ private static final List KNOWN_OS = List.of("darwin", "windows", "linux");
+ private static final List KNOWN_ARCH = List.of("amd64", "arm64");
+
+ public static CommunityGrantPlatform current() {
+ return of(System.getProperty("os.name", ""), System.getProperty("os.arch", ""));
+ }
+
+ static CommunityGrantPlatform of(String rawOsName, String rawOsArch) {
+ String osName = rawOsName.toLowerCase(Locale.ROOT);
+ String osArch = rawOsArch.toLowerCase(Locale.ROOT);
+ String os;
+ if (osName.contains("mac") || osName.contains("darwin")) {
+ os = "darwin";
+ } else if (osName.contains("win")) {
+ os = "windows";
+ } else {
+ os = "linux";
+ }
+ String arch;
+ if (osArch.contains("aarch64") || osArch.contains("arm64")) {
+ arch = "arm64";
+ } else if (osArch.contains("amd64") || osArch.contains("x86_64") || osArch.contains("x64")) {
+ arch = "amd64";
+ } else {
+ throw new IllegalStateException("Unsupported architecture for the instance checker: " + osArch);
+ }
+ return new CommunityGrantPlatform(os, arch);
+ }
+
+ public String checkerFileName() {
+ return "windows".equals(os) ? "tb-instance-check.exe" : "tb-instance-check";
+ }
+
+ /** A legibility check, not a security one: true only for a name that spells out another os or arch. */
+ public boolean namesAnotherPlatform(String fileName) {
+ if (StringUtils.isEmpty(fileName)) {
+ return false;
+ }
+ String normalized = fileName.toLowerCase(Locale.ROOT);
+ return namesAnother(normalized, KNOWN_OS, os) || namesAnother(normalized, KNOWN_ARCH, arch);
+ }
+
+ private static boolean namesAnother(String fileName, List known, String mine) {
+ return known.stream().anyMatch(token -> !token.equals(mine) && fileName.contains(token));
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java
new file mode 100644
index 0000000000..a19f4e3163
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java
@@ -0,0 +1,547 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import jakarta.annotation.PreDestroy;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.thingsboard.common.util.ThingsBoardExecutors;
+import org.thingsboard.server.common.data.StringUtils;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantMode;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantState;
+import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.msg.queue.ServiceType;
+import org.thingsboard.server.dao.subscription.TbClusterStore;
+import org.thingsboard.server.queue.discovery.PartitionService;
+import org.thingsboard.server.queue.discovery.TbApplicationEventListener;
+import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent;
+import org.thingsboard.server.queue.util.AfterStartUp;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.UnaryOperator;
+
+/**
+ * Polls the portal about this deployment's claim and projects the answer onto the local state. Only the node
+ * owning the system tenant's TB_CORE partition runs the loop; it supervises for flows other nodes began.
+ * On the offline rail it never calls out, and only enforces the sign-up deadline.
+ */
+@Component
+@TbCoreComponent
+@RequiredArgsConstructor
+@Slf4j
+public class CommunityGrantPoller extends TbApplicationEventListener {
+
+ static final long MIN_POLL_INTERVAL_MS = 2000;
+ static final int MAX_RETRY_AFTER_SEC = 3600;
+ static final long MAX_FAILURE_BACKOFF_MS = TimeUnit.MINUTES.toMillis(10);
+ static final int CONSECUTIVE_FAILURE_WARN_THRESHOLD = 5;
+
+ static final int MAX_POLL_FAILURES = 200;
+
+ /** Several of these failures are permanent, and every retry re-downloads the whole checker. */
+ static final int MAX_VERIFICATION_FAILURES = 5;
+
+ @Value("${community-grant.enabled:true}")
+ private boolean enabled;
+
+ @Value("${community-grant.fast-poll-interval-ms:3000}")
+ private long fastPollIntervalMs;
+
+ @Value("${community-grant.fast-poll-window-ms:120000}")
+ private long fastPollWindowMs;
+
+ @Value("${community-grant.slow-poll-interval-ms:30000}")
+ private long slowPollIntervalMs;
+
+ /** Matched to the portal's claim-token lifetime (24h). */
+ @Value("${community-grant.sign-up-deadline-ms:86400000}")
+ private long signUpDeadlineMs;
+
+ @Value("${community-grant.supervise-interval-ms:30000}")
+ private long superviseIntervalMs;
+
+ private final PartitionService partitionService;
+ private final TbClusterStore tbClusterStore;
+ private final CommunityGrantFlowStateStore flowStateStore;
+ private final CommunityGrantPortalClient portalClient;
+ private final CommunityGrantReportRunner reportRunner;
+
+ private final ScheduledExecutorService scheduler =
+ ThingsBoardExecutors.newSingleThreadScheduledExecutor("tb-community-grant-poller");
+ private final AtomicBoolean armed = new AtomicBoolean(false);
+ private final ReentrantLock pollLock = new ReentrantLock();
+ private final AtomicInteger consecutiveFailures = new AtomicInteger(0);
+ private final AtomicInteger verificationFailures = new AtomicInteger(0);
+
+ /** Stops a poll still running across a disarm and re-arm from rescheduling beside the new chain. */
+ private final AtomicLong generation = new AtomicLong();
+
+ private volatile ScheduledFuture> pendingPoll;
+ private volatile ScheduledFuture> supervisor;
+ private volatile long pollingSince;
+ private volatile long lastPollTs;
+
+ /** The claim token the current budgets and fast window belong to. */
+ private volatile String pollingToken;
+
+ @AfterStartUp(order = AfterStartUp.REGULAR_SERVICE)
+ public void init() {
+ if (enabled && isSystemTenantPartitionMine()) {
+ startSupervising();
+ armIfPollable();
+ }
+ }
+
+ @Override
+ protected void onTbApplicationEvent(PartitionChangeEvent event) {
+ if (!enabled) {
+ return;
+ }
+ if (isSystemTenantPartitionMine()) {
+ startSupervising();
+ armIfPollable();
+ } else {
+ stopSupervising();
+ disarm();
+ }
+ }
+
+ @Override
+ protected boolean filterTbApplicationEvent(PartitionChangeEvent event) {
+ return ServiceType.TB_CORE == event.getServiceType();
+ }
+
+ /** A no-op off the partition owner, whose supervisor picks the flow up instead. Arms offline flows too. */
+ public void arm() {
+ if (!enabled) {
+ return;
+ }
+ if (!isSystemTenantPartitionMine()) {
+ log.debug("Not arming the community grant poller: this node does not own the system tenant's "
+ + "TB_CORE partition");
+ return;
+ }
+ if (armed.compareAndSet(false, true)) {
+ pollingSince = System.currentTimeMillis();
+ verificationFailures.set(0);
+ consecutiveFailures.set(0);
+ cancelPendingPoll();
+ schedule(fastPollIntervalMs, generation.incrementAndGet());
+ }
+ }
+
+ public void disarm() {
+ armed.set(false);
+ cancelPendingPoll();
+ }
+
+ boolean isArmed() {
+ return armed.get();
+ }
+
+ @PreDestroy
+ public void stop() {
+ stopSupervising();
+ disarm();
+ scheduler.shutdownNow();
+ }
+
+ private synchronized void startSupervising() {
+ if (supervisor != null) {
+ return;
+ }
+ try {
+ supervisor = scheduler.scheduleWithFixedDelay(this::supervise,
+ superviseIntervalMs, superviseIntervalMs, TimeUnit.MILLISECONDS);
+ } catch (Exception e) {
+ log.warn("Failed to schedule the community grant supervisor", e);
+ }
+ }
+
+ private synchronized void stopSupervising() {
+ ScheduledFuture> pending = supervisor;
+ if (pending != null) {
+ pending.cancel(false);
+ supervisor = null;
+ }
+ }
+
+ void supervise() {
+ try {
+ if (!armed.get()) {
+ armIfPollable();
+ }
+ } catch (Throwable e) {
+ // A fixed-delay task that throws is never run again.
+ log.debug("The community grant supervisor tick failed", e);
+ }
+ }
+
+ private boolean isSystemTenantPartitionMine() {
+ try {
+ return partitionService.resolve(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID).isMyPartition();
+ } catch (Exception e) {
+ log.debug("Failed to resolve the system tenant partition", e);
+ return false;
+ }
+ }
+
+ /** Offline, nothing ever answers past the sign-up form, so there is no work left once it is done. */
+ private static boolean hasWorkLeft(CommunityGrantFlowState state) {
+ return state.getMode() != CommunityGrantMode.OFFLINE
+ || state.getState() == CommunityGrantState.AWAITING_SIGNUP;
+ }
+
+ private void armIfPollable() {
+ boolean pollable;
+ try {
+ CommunityGrantFlowState stored = flowStateStore.get();
+ pollable = stored.getState().isPollable() && hasWorkLeft(stored);
+ } catch (Exception e) {
+ log.warn("Failed to read the stored community grant state, not arming the community grant poller", e);
+ return;
+ }
+ if (pollable) {
+ arm();
+ }
+ }
+
+ private void schedule(long delayMs, long gen) {
+ if (!armed.get() || gen != generation.get()) {
+ return;
+ }
+ try {
+ pendingPoll = scheduler.schedule(() -> pollAndReschedule(gen), delayMs, TimeUnit.MILLISECONDS);
+ } catch (Exception e) {
+ // Cleared so arm() can start a new chain.
+ armed.set(false);
+ log.warn("Failed to schedule the next community grant poll", e);
+ }
+ }
+
+ private void cancelPendingPoll() {
+ ScheduledFuture> pending = pendingPoll;
+ if (pending != null) {
+ pending.cancel(false);
+ pendingPoll = null;
+ }
+ }
+
+ void pollAndReschedule() {
+ pollAndReschedule(generation.get());
+ }
+
+ private void pollAndReschedule(long gen) {
+ if (gen != generation.get()) {
+ return;
+ }
+ long nextDelay;
+ try {
+ nextDelay = nextDelay(poll());
+ } catch (Throwable e) {
+ // Throwable, so an Error cannot cancel the scheduled task.
+ int failures = consecutiveFailures.incrementAndGet();
+ if (failures >= CONSECUTIVE_FAILURE_WARN_THRESHOLD) {
+ log.warn("Failed to poll the license portal ({} consecutive failures)", failures, e);
+ } else {
+ log.debug("Failed to poll the license portal", e);
+ }
+ onPollFailure(failures);
+ nextDelay = failureDelay(failures);
+ }
+ schedule(nextDelay, gen);
+ }
+
+ /** An unreachable portal never answers, so its endings are enforced locally. */
+ private void onPollFailure(int failures) {
+ try {
+ String token = tbClusterStore.getLicenseClaimToken().orElse(null);
+ if (StringUtils.isEmpty(token)) {
+ return;
+ }
+ long now = System.currentTimeMillis();
+ if (parkIfSignUpAbandoned(token, flowStateStore.get(), now)) {
+ return;
+ }
+ if (failures >= MAX_POLL_FAILURES) {
+ log.warn("Parking the community grant flow after {} consecutive poll failures", failures);
+ park(token, now, CommunityGrantParkReason.PORTAL_UNREACHABLE);
+ }
+ } catch (Exception e) {
+ log.debug("Failed to park the community grant flow after a poll failure", e);
+ }
+ }
+
+ /**
+ * @return the portal's own pacing instruction, or {@code null} when this tick did not reach it.
+ */
+ Integer poll() {
+ if (!armed.get()) {
+ return null;
+ }
+ String token = tbClusterStore.getLicenseClaimToken().orElse(null);
+ if (StringUtils.isEmpty(token)) {
+ disarm();
+ return null;
+ }
+ if (!token.equals(pollingToken)) {
+ // A new token is a new enrollment. Re-based here: on another node, the owner never sees start().
+ if (pollingToken != null) {
+ pollingSince = System.currentTimeMillis();
+ verificationFailures.set(0);
+ consecutiveFailures.set(0);
+ }
+ pollingToken = token;
+ }
+ CommunityGrantFlowState current = flowStateStore.get();
+ if (current.getMode() == CommunityGrantMode.OFFLINE) {
+ if (!hasWorkLeft(current)) {
+ disarm();
+ return null;
+ }
+ parkIfSignUpAbandoned(token, current, System.currentTimeMillis());
+ return null;
+ }
+ UUID clusterId = tbClusterStore.getClusterId().orElse(null);
+ if (clusterId == null) {
+ disarm();
+ return null;
+ }
+ if (System.currentTimeMillis() - lastPollTs < MIN_POLL_INTERVAL_MS || !pollLock.tryLock()) {
+ return null;
+ }
+ try {
+ lastPollTs = System.currentTimeMillis();
+ CommunityGrantPortalStatus status = portalClient.getStatus(token, clusterId);
+ // Reset only once the portal has actually answered.
+ consecutiveFailures.set(0);
+ if (status == null) {
+ return null;
+ }
+ apply(token, status);
+ return status.retryAfterSec();
+ } finally {
+ pollLock.unlock();
+ }
+ }
+
+ /** The portal's {@code retryAfterSec}, when positive, wins over the local cadence. */
+ long nextDelay(Integer retryAfterSec) {
+ if (retryAfterSec != null && retryAfterSec > 0) {
+ return TimeUnit.SECONDS.toMillis(Math.min(retryAfterSec, MAX_RETRY_AFTER_SEC));
+ }
+ return System.currentTimeMillis() - pollingSince < fastPollWindowMs ? fastPollIntervalMs : slowPollIntervalMs;
+ }
+
+ long failureDelay(int failures) {
+ return Math.min(nextDelay(null) << Math.min(failures - 1, 10), MAX_FAILURE_BACKOFF_MS);
+ }
+
+ void apply(String token, CommunityGrantPortalStatus status) {
+ long now = System.currentTimeMillis();
+ String statusValue = status.status();
+ if (statusValue == null) {
+ // An empty or partial 200 body.
+ log.debug("Ignoring a portal status response with no status value");
+ return;
+ }
+ if (applyIfTerminal(token, statusValue, now)) {
+ return;
+ }
+ switch (statusValue) {
+ case "AWAITING_SIGNUP" -> onAwaitingSignup(token, now);
+ case "VERIFICATION_REQUIRED" -> onVerificationRequired(token, status, now);
+ case "UNDER_REVIEW" -> onUnderReview(token, now);
+ case "EXPIRED" -> park(token, now, CommunityGrantParkReason.LINK_EXPIRED);
+ default -> log.debug("Ignoring an unrecognized portal status");
+ }
+ }
+
+ /** @return whether the status was a terminal one, even when the flow could not be ended on this poll. */
+ private boolean applyIfTerminal(String token, String status, long now) {
+ CommunityGrantState terminalState = terminalStateFor(status);
+ if (terminalState == null) {
+ return false;
+ }
+ if (terminalState == CommunityGrantState.REGISTERED) {
+ onDone(token, now);
+ } else {
+ retire(token, terminalState, now, null);
+ }
+ return true;
+ }
+
+ /** The key is stored before the token is cleared, so a failure above it leaves the next poll to retry. */
+ private void onDone(String token, long now) {
+ String licenseSecret;
+ try {
+ licenseSecret = portalClient.claimLicense(token);
+ } catch (CommunityGrantLicenseClaimRefusedException e) {
+ log.warn("The license portal did not hand over the license key for this registration ({}). "
+ + "The registration stands and the key can be entered by hand later", e.getMessage());
+ retire(token, CommunityGrantState.REGISTERED, now, null);
+ return;
+ }
+ if (StringUtils.isEmpty(licenseSecret)) {
+ return;
+ }
+ tbClusterStore.saveLicenseSecret(licenseSecret);
+ retire(token, CommunityGrantState.REGISTERED, now, null);
+ }
+
+ /** @return the state the flow ends in, or {@code null} if the status is not a terminal one. */
+ private static CommunityGrantState terminalStateFor(String status) {
+ return switch (status) {
+ case "DONE" -> CommunityGrantState.REGISTERED;
+ case "WRONG_INSTALLATION" -> CommunityGrantState.WRONG_INSTALLATION;
+ default -> null;
+ };
+ }
+
+ /** The portal cannot tell an unfinished sign-up from an abandoned one, so the deadline is enforced here. */
+ private void onAwaitingSignup(String token, long now) {
+ if (parkIfSignUpAbandoned(token, flowStateStore.get(), now)) {
+ return;
+ }
+ applyIfCurrent(token, state -> {
+ state.setState(CommunityGrantState.AWAITING_SIGNUP);
+ state.setLastPolledAt(now);
+ return state;
+ });
+ }
+
+ /** @return whether the flow was parked. */
+ private boolean parkIfSignUpAbandoned(String token, CommunityGrantFlowState current, long now) {
+ Long startedAt = current.getStartedAt();
+ if (current.getState() != CommunityGrantState.AWAITING_SIGNUP
+ || startedAt == null || now - startedAt <= signUpDeadlineMs) {
+ return false;
+ }
+ park(token, now, CommunityGrantParkReason.SIGNUP_ABANDONED);
+ return true;
+ }
+
+ private void onVerificationRequired(String token, CommunityGrantPortalStatus status, long now) {
+ CommunityGrantFlowState updated = applyIfCurrent(token, state -> {
+ // The portal asks for verification until a by-hand report lands; that state must not be overwritten.
+ if (state.getState() != CommunityGrantState.VALIDATING
+ && state.getState() != CommunityGrantState.REPORT_HANDED_OVER) {
+ state.setState(CommunityGrantState.COLLECTING);
+ }
+ state.setLastPolledAt(now);
+ return state;
+ });
+ if (updated == null) {
+ return;
+ }
+ if (updated.getMode() == CommunityGrantMode.OFFLINE) {
+ return;
+ }
+ if (updated.getState() == CommunityGrantState.VALIDATING) {
+ // A by-hand report is already in flight.
+ return;
+ }
+ Optional checkerInput = CommunityGrantCheckerInput.from(status.checkerInput());
+ if (checkerInput.isEmpty()) {
+ log.warn("The portal asked for verification without the input needed to produce it");
+ return;
+ }
+ String uploadedStatus;
+ try {
+ uploadedStatus = reportRunner.runAndUpload(token, checkerInput.get());
+ } catch (Exception e) {
+ int failures = verificationFailures.incrementAndGet();
+ if (failures < MAX_VERIFICATION_FAILURES) {
+ log.warn("Failed to produce and upload the instance check", e);
+ } else if (updated.getState() == CommunityGrantState.REPORT_HANDED_OVER) {
+ // Parking would retire the token the handed-over report is bound to.
+ log.warn("The instance check keeps failing ({} attempts), but the report has been handed over "
+ + "by hand, so the flow is left waiting on the portal", failures, e);
+ } else {
+ log.warn("Parking the community grant flow after {} failed instance checks", failures, e);
+ park(token, now, CommunityGrantParkReason.CHECK_FAILED);
+ }
+ return;
+ }
+ verificationFailures.set(0);
+ if (uploadedStatus == null) {
+ return;
+ }
+ if (applyIfTerminal(token, uploadedStatus, now)) {
+ return;
+ }
+ if ("UNDER_REVIEW".equals(uploadedStatus)) {
+ onUnderReview(token, now);
+ } else {
+ log.debug("Ignoring an unrecognized portal status after the upload");
+ }
+ }
+
+ /** A wait, not an ending: the token is kept for the poll that brings the reviewer's decision. */
+ private void onUnderReview(String token, long now) {
+ applyIfCurrent(token, state -> {
+ state.setState(CommunityGrantState.UNDER_REVIEW);
+ state.setLastPolledAt(now);
+ return state;
+ });
+ }
+
+ /** @return the state as written, or {@code null} if the claim token had been replaced. */
+ private CommunityGrantFlowState applyIfCurrent(String token, UnaryOperator updater) {
+ AtomicBoolean applied = new AtomicBoolean();
+ CommunityGrantFlowState updated = flowStateStore.update(state -> {
+ // Checked under the store's lock, so a start() on this node cannot replace the token mid-write.
+ applied.set(token.equals(tbClusterStore.getLicenseClaimToken().orElse(null)));
+ return applied.get() ? updater.apply(state) : state;
+ });
+ if (!applied.get()) {
+ log.debug("Ignoring a portal answer for a claim token that has since been replaced");
+ return null;
+ }
+ return updated;
+ }
+
+ private void park(String token, long now, CommunityGrantParkReason reason) {
+ retire(token, CommunityGrantState.RESUME, now, reason);
+ }
+
+ /** The state is written before the token is cleared, so a failed write leaves the next poll to retry. */
+ private void retire(String token, CommunityGrantState newState, long now, CommunityGrantParkReason reason) {
+ AtomicBoolean applied = new AtomicBoolean();
+ flowStateStore.update(state -> {
+ // Checked under the store's lock, so a start() on this node cannot replace the token mid-write.
+ applied.set(token.equals(tbClusterStore.getLicenseClaimToken().orElse(null)));
+ if (!applied.get()) {
+ return state;
+ }
+ // The portal still serves a finished grant's page on this link.
+ String registrationLink = newState == CommunityGrantState.REGISTERED ? state.getSignUpUrl() : null;
+ state.setState(newState);
+ state.setParkReason(reason);
+ state.clearClaim();
+ state.setSignUpUrl(registrationLink);
+ state.setLastPolledAt(now);
+ return state;
+ });
+ if (!applied.get()) {
+ log.debug("Ignoring a portal answer for a claim token that has since been replaced");
+ return;
+ }
+ tbClusterStore.clearLicenseClaimToken(token);
+ disarm();
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java
new file mode 100644
index 0000000000..ea5410220f
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java
@@ -0,0 +1,294 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import jakarta.annotation.PostConstruct;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.web.client.RestTemplateBuilder;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.client.ClientHttpRequest;
+import org.springframework.http.client.ClientHttpResponse;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.DefaultResponseErrorHandler;
+import org.springframework.web.client.HttpStatusCodeException;
+import org.springframework.web.client.ResourceAccessException;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.util.UriComponentsBuilder;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantMode;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.time.Duration;
+import java.util.UUID;
+
+/**
+ * The only outbound path to the license portal. Calls that carry grant state are authenticated by the claim
+ * token, never by the cluster id, which is not a secret.
+ */
+@Component
+@TbCoreComponent
+@Slf4j
+public class CommunityGrantPortalClient {
+
+ private static final String BASE_PATH = "/api/noauth/communityGrant";
+ private static final String CLUSTER_STATUS_PATH = BASE_PATH + "/clusterStatus?clusterId={clusterId}";
+ private static final String LICENSE_CLAIM_PATH = "/api/noauth/freeLicense/claim";
+
+ /** A header rather than a query parameter, which would be written to access and proxy logs. */
+ private static final String CLAIM_TOKEN_HEADER = "X-TB-Claim-Token";
+
+ private static final UUID REACHABILITY_PROBE_CLUSTER_ID = new UUID(0L, 0L);
+
+ private static final int REACHABILITY_PROBE_MAX_BODY_BYTES = 4096;
+
+ private static final int ERROR_BODY_MAX_BYTES = 4096;
+
+ @Value("${community-grant.enabled:true}")
+ private boolean enabled;
+
+ @Value("${community-grant.base-url:https://license.thingsboard.io}")
+ private String baseUrl;
+
+ @Value("${community-grant.connect-timeout-sec:5}")
+ private int connectTimeoutSec;
+
+ @Value("${community-grant.read-timeout-sec:10}")
+ private int readTimeoutSec;
+
+ @Value("${community-grant.max-checker-size-bytes:33554432}")
+ private long maxCheckerSizeBytes;
+
+ private RestTemplate restTemplate;
+
+ @PostConstruct
+ public void initRestClient() {
+ // Validation failure stops the node, so a disabled feature does not validate its URL.
+ if (enabled) {
+ baseUrl = normalizeBaseUrl(baseUrl);
+ }
+ restTemplate = new RestTemplateBuilder()
+ .connectTimeout(Duration.ofSeconds(connectTimeoutSec))
+ .readTimeout(Duration.ofSeconds(readTimeoutSec))
+ .errorHandler(new BoundedBodyErrorHandler())
+ .build();
+ }
+
+ /** Spring's default handler buffers an error body in full. */
+ private static class BoundedBodyErrorHandler extends DefaultResponseErrorHandler {
+
+ @Override
+ protected byte[] getResponseBody(ClientHttpResponse response) {
+ try (InputStream in = response.getBody()) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[1024];
+ int read;
+ while (out.size() < ERROR_BODY_MAX_BYTES && (read = in.read(buffer)) != -1) {
+ out.write(buffer, 0, read);
+ }
+ return out.toByteArray();
+ } catch (IOException e) {
+ return new byte[0];
+ }
+ }
+ }
+
+ /** A trailing slash would 404 every route, and the reachability probe counts a 404 as reachable. */
+ private static String normalizeBaseUrl(String configured) {
+ String normalized = configured == null ? "" : configured.trim().replaceAll("/+$", "");
+ URI uri;
+ try {
+ uri = new URI(normalized);
+ } catch (URISyntaxException e) {
+ throw new IllegalStateException("community-grant.base-url is not a valid URL: " + configured, e);
+ }
+ if (uri.getHost() == null || !("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))) {
+ throw new IllegalStateException("community-grant.base-url must be an absolute http(s) URL: " + configured);
+ }
+ return normalized;
+ }
+
+ public String getPortalUrl() {
+ return baseUrl;
+ }
+
+ /**
+ * The platform rides along on every link, not only an offline one: the portal needs it to build a checker
+ * bundle if the enrollment later moves to the by-hand route.
+ *
+ * @throws IllegalArgumentException if {@code community-grant.base-url} cannot be parsed
+ */
+ public String buildSignUpUrl(UUID clusterId, String token, CommunityGrantMode mode) {
+ UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl)
+ .path("/communityGrant")
+ .queryParam("clusterId", clusterId)
+ .queryParam("claimToken", token);
+ if (mode == CommunityGrantMode.OFFLINE) {
+ builder.queryParam("offline", true);
+ }
+ appendPlatform(builder);
+ return builder.build().toUriString();
+ }
+
+ /** Omitted on an architecture with no checker build rather than failing the enrollment. */
+ private static void appendPlatform(UriComponentsBuilder builder) {
+ CommunityGrantPlatform platform;
+ try {
+ platform = CommunityGrantPlatform.current();
+ } catch (RuntimeException e) {
+ log.debug("Leaving the platform out of the community grant sign-up link", e);
+ return;
+ }
+ builder.queryParam("os", platform.os()).queryParam("arch", platform.arch());
+ }
+
+ /** Only a transport failure counts as unreachable; any HTTP status means reachable. */
+ public boolean isPortalReachable() {
+ String url = baseUrl + CLUSTER_STATUS_PATH;
+ try {
+ restTemplate.execute(url, HttpMethod.GET, null, response -> {
+ try (InputStream in = response.getBody()) {
+ byte[] buffer = new byte[1024];
+ int total = 0;
+ int read;
+ while (total < REACHABILITY_PROBE_MAX_BODY_BYTES && (read = in.read(buffer)) != -1) {
+ total += read;
+ }
+ }
+ return null;
+ }, REACHABILITY_PROBE_CLUSTER_ID);
+ return true;
+ } catch (HttpStatusCodeException e) {
+ return true;
+ } catch (RestClientException e) {
+ log.info("The license portal is not reachable from this server: {}", e.getMessage());
+ return false;
+ }
+ }
+
+ public boolean isAlreadyRegistered(UUID clusterId) {
+ String url = baseUrl + CLUSTER_STATUS_PATH;
+ CommunityGrantClusterStatus response = restTemplate.getForObject(url, CommunityGrantClusterStatus.class, clusterId);
+ return response != null && response.alreadyRegistered();
+ }
+
+ /** The portal always answers a bare 200, so a registration is never confirmed to the caller. */
+ public void requestAccess(UUID clusterId) {
+ String url = baseUrl + BASE_PATH + "/requestAccess?clusterId={clusterId}";
+ restTemplate.postForObject(url, null, Void.class, clusterId);
+ }
+
+ /**
+ * The cluster id goes with every poll: the token resolves to an account whose grant may belong to a
+ * different installation.
+ *
+ * @return the portal's parsed answer, or {@code null} if the portal answered with an empty body
+ */
+ public CommunityGrantPortalStatus getStatus(String token, UUID clusterId) {
+ String url = baseUrl + BASE_PATH + "/status?clusterId={clusterId}";
+ HttpHeaders headers = new HttpHeaders();
+ headers.set(CLAIM_TOKEN_HEADER, token);
+ return restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers),
+ CommunityGrantPortalStatus.class, clusterId).getBody();
+ }
+
+ /**
+ * @return the portal's status after it accepted the report, or {@code null} if the portal answered with
+ * an empty body.
+ */
+ public String uploadReport(String token, String report) {
+ String url = baseUrl + BASE_PATH + "/report";
+ CommunityGrantReportResponse response = restTemplate.postForObject(url,
+ new CommunityGrantReportRequest(token, report), CommunityGrantReportResponse.class);
+ return response == null ? null : response.status();
+ }
+
+ /**
+ * This route reads the claim token from the body, not from the header the grant routes use.
+ *
+ * @return the granted license key, or {@code null} while the portal has none to hand over yet
+ * @throws CommunityGrantLicenseClaimRefusedException if the portal refuses the claim
+ */
+ public String claimLicense(String token) {
+ String url = baseUrl + LICENSE_CLAIM_PATH;
+ CommunityGrantLicenseClaimResponse response;
+ try {
+ response = restTemplate.postForObject(url, new CommunityGrantLicenseClaimRequest(token),
+ CommunityGrantLicenseClaimResponse.class);
+ } catch (HttpStatusCodeException e) {
+ // A rate-limited claim is the one client error that is worth trying again.
+ if (e.getStatusCode().is4xxClientError()
+ && e.getStatusCode().value() != HttpStatus.TOO_MANY_REQUESTS.value()) {
+ throw new CommunityGrantLicenseClaimRefusedException(e);
+ }
+ throw e;
+ }
+ return response != null && response.activated() ? response.secret() : null;
+ }
+
+ /**
+ * @throws CommunityGrantCheckerTooLargeException if the checker exceeds {@code maxCheckerSizeBytes}
+ * @throws ResourceAccessException if reading the stream fails
+ */
+ public byte[] downloadChecker(String token, String os, String arch) {
+ return download(BASE_PATH + "/checker?os={os}&arch={arch}", "instance checker", token, os, arch);
+ }
+
+ /**
+ * @throws HttpStatusCodeException if the portal has no signature staged for this platform
+ */
+ public byte[] downloadCheckerSignature(String token, String os, String arch) {
+ return download(BASE_PATH + "/checkerSignature?os={os}&arch={arch}",
+ "instance checker's release signature", token, os, arch);
+ }
+
+ private byte[] download(String path, String what, String token, String os, String arch) {
+ String url = baseUrl + path;
+ final long limit = maxCheckerSizeBytes;
+ return restTemplate.execute(url, HttpMethod.GET, request -> setClaimToken(request, token), response -> {
+ long contentLength = response.getHeaders().getContentLength();
+ if (contentLength > limit) {
+ throw new CommunityGrantCheckerTooLargeException("The " + what + " size " + contentLength
+ + " bytes exceeds the configured limit of " + limit + " bytes");
+ }
+ int initialCapacity = contentLength > 0 && contentLength <= Integer.MAX_VALUE
+ ? (int) contentLength : 8192;
+ ByteArrayOutputStream out = new ByteArrayOutputStream(initialCapacity);
+ boolean complete = false;
+ try (InputStream in = response.getBody()) {
+ byte[] buffer = new byte[8192];
+ long total = 0;
+ int read;
+ while ((read = in.read(buffer)) != -1) {
+ total += read;
+ if (total > limit) {
+ throw new CommunityGrantCheckerTooLargeException("The " + what
+ + " stream exceeded the configured limit of " + limit + " bytes");
+ }
+ out.write(buffer, 0, read);
+ }
+ complete = true;
+ } catch (IOException e) {
+ if (!complete) {
+ throw new ResourceAccessException("Failed to read the " + what + " (GET " + url + ")", e);
+ }
+ // Only close() failed after a complete read; the download is kept.
+ log.debug("Failed to close the {} response stream after a complete read", what, e);
+ }
+ return out.toByteArray();
+ }, os, arch);
+ }
+
+ private static void setClaimToken(ClientHttpRequest request, String token) {
+ request.getHeaders().set(CLAIM_TOKEN_HEADER, token);
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java
new file mode 100644
index 0000000000..755ee5a322
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java
@@ -0,0 +1,16 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.databind.JsonNode;
+
+/**
+ * The portal's answer to a poll. {@code status} is a raw string so an unknown value leaves the flow where it
+ * is rather than failing deserialization.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public record CommunityGrantPortalStatus(String status,
+ JsonNode checkerInput,
+ Integer retryAfterSec) {
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java
new file mode 100644
index 0000000000..309efb6565
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java
@@ -0,0 +1,212 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import jakarta.annotation.PostConstruct;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.PublicKey;
+import java.security.Signature;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Verifies the instance checker's detached release signature against the configured release-signing keys.
+ * Fails closed: with no trusted key, every checker is refused.
+ */
+@Component
+@TbCoreComponent
+@Slf4j
+public class CommunityGrantReleaseSignatureVerifier {
+
+ static final String PUBLIC_KEYS_PROPERTY = "community-grant.checker-release-public-keys";
+
+ /** The whole signature file: {@code MAGIC(8) ‖ VERSION(1) ‖ KEYID(1) ‖ SIG(64)}, and nothing after it. */
+ static final int SIGNATURE_FILE_LENGTH = 74;
+
+ private static final byte[] MAGIC = {'T', 'B', 'I', 'C', 'S', 'I', 'G', '1'};
+ private static final int VERSION_OFFSET = 8;
+ private static final byte SUPPORTED_VERSION = 0x01;
+ private static final int KEY_ID_OFFSET = 9;
+ private static final int SIGNATURE_OFFSET = 10;
+
+ private static final int ED25519_PUBLIC_KEY_LENGTH = 32;
+
+ /** RFC 8410 SubjectPublicKeyInfo prefix for a raw 32-byte Ed25519 key; KeyFactory takes no raw spec. */
+ private static final byte[] ED25519_SPKI_PREFIX = {
+ 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00
+ };
+
+ @Value("${" + PUBLIC_KEYS_PROPERTY + ":}")
+ private String checkerReleasePublicKeys;
+
+ /** Empty when nothing is configured and when the configured value could not be parsed. */
+ private Map trustStore = Map.of();
+
+ private String trustStoreError;
+
+ @PostConstruct
+ void init() {
+ try {
+ trustStore = parsePublicKeys(checkerReleasePublicKeys);
+ trustStoreError = null;
+ } catch (IllegalArgumentException e) {
+ trustStore = Map.of();
+ trustStoreError = e.getMessage();
+ log.error("{} could not be parsed, so no release-signing key is trusted and every "
+ + "instance checker will be refused: {}", PUBLIC_KEYS_PROPERTY, e.getMessage());
+ }
+ }
+
+ public boolean hasTrustedKeys() {
+ return !trustStore.isEmpty();
+ }
+
+ /**
+ * Throws {@link IllegalArgumentException} unless {@code signatureData} is a valid release signature over
+ * exactly {@code checkerData} under a trusted key. Messages are safe to show the uploader and to audit.
+ */
+ public void verify(byte[] checkerData, byte[] signatureData) {
+ if (checkerData == null || checkerData.length == 0) {
+ throw new IllegalArgumentException("The uploaded instance checker is empty, so there is nothing "
+ + "to verify. It was not run.");
+ }
+ if (signatureData == null || signatureData.length == 0) {
+ throw new IllegalArgumentException("The enrollment bundle carries no release signature for the "
+ + "instance checker, so it could not be verified and was not run. Download the enrollment "
+ + "bundle for this platform again from the License Portal.");
+ }
+ if (signatureData.length != SIGNATURE_FILE_LENGTH) {
+ throw new IllegalArgumentException("The release signature is " + signatureData.length
+ + " bytes; a ThingsBoard release signature is exactly " + SIGNATURE_FILE_LENGTH
+ + " bytes. The uploaded instance checker was not run. Download the enrollment bundle again "
+ + "from the License Portal and upload it unmodified.");
+ }
+ if (!Arrays.equals(signatureData, 0, MAGIC.length, MAGIC, 0, MAGIC.length)) {
+ throw new IllegalArgumentException("The release signature is not a ThingsBoard release "
+ + "signature. The uploaded instance checker was not run. Download the enrollment bundle again "
+ + "from the License Portal and upload it unmodified.");
+ }
+ byte version = signatureData[VERSION_OFFSET];
+ if (version != SUPPORTED_VERSION) {
+ throw new IllegalArgumentException("The release signature declares signature format "
+ + "version " + (version & 0xFF) + "; this deployment only understands version "
+ + SUPPORTED_VERSION + ". The uploaded instance checker was not run. Upgrade ThingsBoard, or "
+ + "use a checker release this version can verify.");
+ }
+ int keyId = signatureData[KEY_ID_OFFSET] & 0xFF;
+ if (keyId == 0) {
+ throw new IllegalArgumentException("The release signature names key id 0, which is "
+ + "reserved and never valid. The uploaded instance checker was not run.");
+ }
+ if (trustStore.isEmpty()) {
+ if (trustStoreError != null) {
+ throw new IllegalArgumentException("The configured " + PUBLIC_KEYS_PROPERTY + " could not be "
+ + "parsed (" + trustStoreError + "), so no uploaded instance checker can be verified. "
+ + "It was not run. Fix the configured value.");
+ }
+ throw new IllegalArgumentException("This deployment is not configured to verify an uploaded "
+ + "instance checker, so it refuses to run one. Set " + PUBLIC_KEYS_PROPERTY + " to the "
+ + "release-signing public key ThingsBoard publishes, as a comma-separated list of "
+ + "keyId:base64PublicKey entries.");
+ }
+ PublicKey publicKey = trustStore.get(keyId);
+ if (publicKey == null) {
+ throw new IllegalArgumentException("The uploaded instance checker is signed under release-signing "
+ + "key id " + keyId + ", which this deployment does not trust. It was not run. Add that "
+ + "key id and its public key to " + PUBLIC_KEYS_PROPERTY + " if ThingsBoard published "
+ + "this release under it.");
+ }
+ byte[] signature = Arrays.copyOfRange(signatureData, SIGNATURE_OFFSET, SIGNATURE_FILE_LENGTH);
+ boolean verified;
+ try {
+ Signature ed25519 = Signature.getInstance("Ed25519");
+ ed25519.initVerify(publicKey);
+ ed25519.update(checkerData);
+ verified = ed25519.verify(signature);
+ } catch (GeneralSecurityException e) {
+ // The JDK throws, rather than returning false, for some invalid encodings.
+ log.debug("An uploaded instance checker's release signature could not be evaluated", e);
+ verified = false;
+ }
+ if (!verified) {
+ throw new IllegalArgumentException("The uploaded instance checker does not match its release "
+ + "signature, so it was not run. Download the enrollment bundle again from the License Portal "
+ + "and upload it unmodified.");
+ }
+ }
+
+ /**
+ * Parses {@code keyId:base64PublicKey[,keyId:base64PublicKey...]}. Every malformed entry throws rather
+ * than being skipped.
+ */
+ static Map parsePublicKeys(String configured) {
+ Map keys = new LinkedHashMap<>();
+ if (configured == null || configured.isBlank()) {
+ return Map.copyOf(keys);
+ }
+ for (String entry : configured.split(",", -1)) {
+ String trimmed = entry.trim();
+ if (trimmed.isEmpty()) {
+ throw new IllegalArgumentException("it has an empty entry; every entry must be "
+ + "keyId:base64PublicKey");
+ }
+ int separator = trimmed.indexOf(':');
+ if (separator < 0) {
+ throw new IllegalArgumentException("an entry is not in the keyId:base64PublicKey form");
+ }
+ int keyId;
+ try {
+ keyId = Integer.parseInt(trimmed.substring(0, separator).trim());
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("an entry's key id is not a number");
+ }
+ if (keyId < 1 || keyId > 255) {
+ throw new IllegalArgumentException("an entry's key id is " + keyId + "; it must be 1-255 "
+ + "(0 is reserved and never valid)");
+ }
+ byte[] raw;
+ try {
+ raw = Base64.getDecoder().decode(trimmed.substring(separator + 1).trim());
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("the public key for key id " + keyId
+ + " is not valid standard base64");
+ }
+ if (raw.length != ED25519_PUBLIC_KEY_LENGTH) {
+ throw new IllegalArgumentException("the public key for key id " + keyId + " decodes to "
+ + raw.length + " bytes; a raw Ed25519 public key is " + ED25519_PUBLIC_KEY_LENGTH
+ + " bytes (it must not be X.509 SubjectPublicKeyInfo-wrapped)");
+ }
+ if (keys.containsKey(keyId)) {
+ throw new IllegalArgumentException("key id " + keyId + " is configured more than once");
+ }
+ keys.put(keyId, ed25519PublicKey(keyId, raw));
+ }
+ return Map.copyOf(keys);
+ }
+
+ /** Probes initVerify here: KeyFactory accepts some off-curve values and only initVerify rejects them. */
+ private static PublicKey ed25519PublicKey(int keyId, byte[] raw) {
+ byte[] encoded = new byte[ED25519_SPKI_PREFIX.length + raw.length];
+ System.arraycopy(ED25519_SPKI_PREFIX, 0, encoded, 0, ED25519_SPKI_PREFIX.length);
+ System.arraycopy(raw, 0, encoded, ED25519_SPKI_PREFIX.length, raw.length);
+ try {
+ PublicKey publicKey = KeyFactory.getInstance("Ed25519")
+ .generatePublic(new X509EncodedKeySpec(encoded));
+ Signature.getInstance("Ed25519").initVerify(publicKey);
+ return publicKey;
+ } catch (GeneralSecurityException e) {
+ throw new IllegalArgumentException("the public key for key id " + keyId
+ + " is not a usable Ed25519 public key");
+ }
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java
new file mode 100644
index 0000000000..1c825a6d59
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+public record CommunityGrantReportRequest(String token, String report) {
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java
new file mode 100644
index 0000000000..221528aa31
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java
@@ -0,0 +1,9 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public record CommunityGrantReportResponse(String status) {
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java
new file mode 100644
index 0000000000..a5a3c23ec8
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java
@@ -0,0 +1,383 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FileUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.info.BuildProperties;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.HttpStatusCodeException;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Fetches or accepts the instance checker, verifies its release signature and runs it against this instance's
+ * own database.
+ */
+@Component
+@TbCoreComponent
+@RequiredArgsConstructor
+@Slf4j
+public class CommunityGrantReportRunner {
+
+ static final String REPORT_HEADER = "-----BEGIN TB INSTANCE CHECK-----";
+ static final String REPORT_FOOTER = "-----END TB INSTANCE CHECK-----";
+
+ private static final int TERMINATION_GRACE_SEC = 5;
+
+ private static final int MAX_STDERR_CAPTURE_BYTES = 8192;
+
+ @Value("${spring.datasource.url}")
+ private String dbUrl;
+
+ @Value("${spring.datasource.username}")
+ private String dbUserName;
+
+ @Value("${spring.datasource.password}")
+ private String dbPassword;
+
+ @Getter
+ @Value("${community-grant.checker-timeout-sec:600}")
+ private int checkerTimeoutSec;
+
+ @Value("${community-grant.max-report-size-bytes:1048576}")
+ private int maxReportSizeBytes;
+
+ @Value("${community-grant.max-checker-size-bytes:33554432}")
+ private long maxCheckerSizeBytes;
+
+ @Autowired(required = false)
+ private BuildProperties buildProperties;
+
+ private final CommunityGrantPortalClient portalClient;
+ private final CommunityGrantReleaseSignatureVerifier releaseSignatureVerifier;
+
+ /**
+ * @return the portal's status after it accepted the report, or {@code null} if the portal answered with
+ * an empty body.
+ */
+ public String runAndUpload(String token, CommunityGrantCheckerInput checkerInput) {
+ Path checker;
+ try {
+ checker = fetchChecker(token);
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to obtain the instance checker", e);
+ }
+ return portalClient.uploadReport(token, runCheckerAndCleanUp(checker, checkerInput));
+ }
+
+ /**
+ * The checks {@link #runUploadedChecker} runs before anything is executed, callable on their own so a
+ * refusal can answer the upload request while the run itself happens later.
+ *
+ * @throws IllegalArgumentException on every refusal
+ */
+ public void verifyUploadedChecker(byte[] checkerData, byte[] signatureData, String fileName) {
+ if (checkerData == null || checkerData.length == 0) {
+ throw new IllegalArgumentException("The uploaded file is empty");
+ }
+ if (checkerData.length > maxCheckerSizeBytes) {
+ throw new IllegalArgumentException("The uploaded file is larger than the configured limit of "
+ + maxCheckerSizeBytes + " bytes");
+ }
+ CommunityGrantPlatform platform = CommunityGrantPlatform.current();
+ if (platform.namesAnotherPlatform(fileName)) {
+ throw new IllegalArgumentException("The uploaded file does not match this server's platform ("
+ + platform.os() + "/" + platform.arch() + ")");
+ }
+ verifyOfflineCheckerSignature(checkerData, signatureData);
+ }
+
+ /** Repeats {@link #verifyUploadedChecker} so nothing unverified reaches disk however this is called. */
+ public String runUploadedChecker(byte[] checkerData, byte[] signatureData, String fileName,
+ CommunityGrantCheckerInput checkerInput) {
+ verifyUploadedChecker(checkerData, signatureData, fileName);
+ CommunityGrantPlatform platform = CommunityGrantPlatform.current();
+ log.info("Running an uploaded instance checker (uploaded file name {}, SHA-256 {})",
+ fileName, HexFormat.of().formatHex(sha256(checkerData)));
+ Path checker;
+ try {
+ checker = writeChecker(checkerData, platform.checkerFileName());
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to store the uploaded file", e);
+ }
+ return runCheckerAndCleanUp(checker, checkerInput);
+ }
+
+ private String runCheckerAndCleanUp(Path checker, CommunityGrantCheckerInput checkerInput) {
+ try {
+ return runChecker(checker, checkerInput);
+ } finally {
+ deleteQuietly(checker);
+ }
+ }
+
+ private void verifyOfflineCheckerSignature(byte[] checkerData, byte[] signatureData) {
+ try {
+ releaseSignatureVerifier.verify(checkerData, signatureData);
+ } catch (IllegalArgumentException e) {
+ log.warn("Refused to run an uploaded instance checker (uploaded file SHA-256 {}): {}",
+ HexFormat.of().formatHex(sha256(checkerData)), e.getMessage());
+ throw e;
+ }
+ }
+
+ private static byte[] sha256(byte[] data) {
+ try {
+ return MessageDigest.getInstance("SHA-256").digest(data);
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 is not available", e);
+ }
+ }
+
+ Path fetchChecker(String token) throws IOException {
+ if (!releaseSignatureVerifier.hasTrustedKeys()) {
+ throw new IllegalStateException("No trusted release-signing key is configured in "
+ + CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY
+ + ", so the instance checker could not be verified and was not run");
+ }
+ CommunityGrantPlatform platform = CommunityGrantPlatform.current();
+ byte[] checkerData = portalClient.downloadChecker(token, platform.os(), platform.arch());
+ verifyDownloadedCheckerSignature(token, platform, checkerData);
+ return writeChecker(checkerData, platform.checkerFileName());
+ }
+
+ private void verifyDownloadedCheckerSignature(String token, CommunityGrantPlatform platform, byte[] checkerData) {
+ byte[] signatureData;
+ try {
+ signatureData = portalClient.downloadCheckerSignature(token, platform.os(), platform.arch());
+ } catch (HttpStatusCodeException e) {
+ throw new IllegalStateException("The portal served no release signature for the instance checker ("
+ + e.getStatusCode() + "), so it could not be verified and was not run", e);
+ }
+ try {
+ releaseSignatureVerifier.verify(checkerData, signatureData);
+ } catch (IllegalArgumentException e) {
+ // The verifier's messages name an uploaded checker.
+ throw new IllegalStateException("The instance checker downloaded from the portal does not match "
+ + "the release signature published for it, so it was not run", e);
+ }
+ }
+
+ Path writeChecker(byte[] checkerData, String fileName) throws IOException {
+ boolean posix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
+ Path dir = posix
+ ? Files.createTempDirectory("tb-instance-check",
+ PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")))
+ : Files.createTempDirectory("tb-instance-check");
+ try {
+ Path checker = dir.resolve(fileName);
+ Files.write(checker, checkerData);
+ if (posix) {
+ Files.setPosixFilePermissions(checker, PosixFilePermissions.fromString("r-x------"));
+ } else if (!checker.toFile().setExecutable(true, true)) {
+ throw new IOException("Failed to make the instance checker executable");
+ }
+ return checker;
+ } catch (IOException | RuntimeException e) {
+ deleteRecursivelyQuietly(dir);
+ throw e;
+ }
+ }
+
+ /**
+ * Secrets travel in the environment, never on the command line, where {@code ps} shows them to every
+ * local user.
+ */
+ String runChecker(Path checker, CommunityGrantCheckerInput checkerInput) {
+ ProcessBuilder processBuilder = new ProcessBuilder(buildCommand(checker));
+ processBuilder.directory(checker.getParent().toFile());
+ prepareCheckerEnvironment(processBuilder.environment(),
+ CommunityGrantLibpqDsn.from(dbUrl, dbUserName, dbPassword), checkerInput);
+
+ Process process;
+ try {
+ process = processBuilder.start();
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to start the instance check", e);
+ }
+ ByteArrayOutputStream stdout = new ByteArrayOutputStream();
+ ByteArrayOutputStream stderr = new ByteArrayOutputStream();
+ AtomicBoolean overflow = new AtomicBoolean(false);
+ Thread stdoutDrain = drainCappedAsync(process.getInputStream(), stdout, overflow, process);
+ Thread stderrDrain = drainBoundedAsync(process.getErrorStream(), stderr);
+ try {
+ process.getOutputStream().close();
+ } catch (IOException e) {
+ log.debug("Failed to close the instance check input stream", e);
+ }
+ boolean exited;
+ try {
+ exited = process.waitFor(checkerTimeoutSec, TimeUnit.SECONDS);
+ if (!exited) {
+ killTree(process);
+ awaitTermination(process);
+ }
+ stdoutDrain.join(TimeUnit.SECONDS.toMillis(TERMINATION_GRACE_SEC));
+ stderrDrain.join(TimeUnit.SECONDS.toMillis(TERMINATION_GRACE_SEC));
+ // Ahead of the timeout: the overflow branch kills the process too.
+ if (overflow.get()) {
+ String ending = "produced more output than the configured limit of " + maxReportSizeBytes + " bytes";
+ logCheckerDiagnostics(stderr, ending);
+ throw new IllegalStateException("The instance check " + ending);
+ }
+ if (!exited) {
+ String ending = "did not finish within " + checkerTimeoutSec + " seconds";
+ logCheckerDiagnostics(stderr, ending);
+ throw new IllegalStateException("The instance check " + ending);
+ }
+ if (stdoutDrain.isAlive()) {
+ // Reading a buffer the drain is still filling could upload a truncated report. stderr is not
+ // checked: a grandchild holding that pipe open would keep its drain alive indefinitely.
+ String ending = "output could not be read back in time";
+ logCheckerDiagnostics(stderr, ending);
+ throw new IllegalStateException("The instance check " + ending);
+ }
+ } catch (InterruptedException e) {
+ killTree(process);
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted while running the instance check", e);
+ }
+ int exitCode = process.exitValue();
+ if (exitCode != 0) {
+ String ending = "failed with exit code " + exitCode;
+ logCheckerDiagnostics(stderr, ending);
+ throw new IllegalStateException("The instance check " + ending);
+ }
+ return readReport(stdout);
+ }
+
+ /** Logged, never put in the exception: it is untrusted child output and the message is shown to the user. */
+ private void logCheckerDiagnostics(ByteArrayOutputStream stderr, String ending) {
+ String diagnostics = stderr.toString(StandardCharsets.UTF_8).trim();
+ if (!diagnostics.isEmpty()) {
+ log.warn("The instance check {}. It wrote to standard error: {}", ending, diagnostics);
+ }
+ }
+
+ private List buildCommand(Path checker) {
+ List command = new ArrayList<>(List.of(checker.toAbsolutePath().toString()));
+ if (buildProperties != null) {
+ command.add("--tb-version");
+ command.add(buildProperties.getVersion());
+ }
+ return command;
+ }
+
+ private static String readReport(ByteArrayOutputStream stdout) {
+ String report = stdout.toString(StandardCharsets.UTF_8).trim();
+ if (!report.startsWith(REPORT_HEADER) || !report.endsWith(REPORT_FOOTER)) {
+ throw new IllegalStateException("The instance check produced unexpected output");
+ }
+ return report;
+ }
+
+ /** Descendants are collected first: once the parent dies they are reparented and no longer found. */
+ private static void killTree(Process process) {
+ List descendants = process.descendants().toList();
+ process.destroyForcibly();
+ descendants.forEach(ProcessHandle::destroyForcibly);
+ }
+
+ /**
+ * Drops the inherited {@code PG*} variables, which could change how the DSN's connection is made.
+ * Case-insensitive because {@link ProcessBuilder#environment()} is on Windows.
+ */
+ static void prepareCheckerEnvironment(Map environment, String dsn,
+ CommunityGrantCheckerInput checkerInput) {
+ environment.keySet().removeIf(name -> name.toUpperCase(Locale.ROOT).startsWith("PG"));
+ environment.put("TB_IC_DSN", dsn);
+ environment.put("TB_IC_INPUT", checkerInput.json());
+ }
+
+ /** On Windows, deleting the binary of a still-exiting process fails. */
+ private void awaitTermination(Process process) {
+ try {
+ if (!process.waitFor(TERMINATION_GRACE_SEC, TimeUnit.SECONDS)) {
+ log.debug("The instance check process did not terminate within {} seconds of being killed",
+ TERMINATION_GRACE_SEC);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ private Thread drainCappedAsync(InputStream in, ByteArrayOutputStream sink, AtomicBoolean overflow,
+ Process process) {
+ return startDaemon("tb-instance-check-stdout", () -> {
+ try (InputStream stream = in) {
+ byte[] buffer = new byte[8192];
+ int read;
+ while ((read = stream.read(buffer)) != -1) {
+ if (sink.size() + read > maxReportSizeBytes) {
+ overflow.set(true);
+ killTree(process);
+ awaitTermination(process);
+ return;
+ }
+ sink.write(buffer, 0, read);
+ }
+ } catch (IOException e) {
+ log.debug("Failed to read the instance check output", e);
+ }
+ });
+ }
+
+ /** Keeps reading past the cap so a chatty checker cannot deadlock on the pipe. */
+ private Thread drainBoundedAsync(InputStream in, ByteArrayOutputStream sink) {
+ return startDaemon("tb-instance-check-stderr", () -> {
+ try (InputStream stream = in) {
+ byte[] buffer = new byte[8192];
+ int read;
+ while ((read = stream.read(buffer)) != -1) {
+ int room = MAX_STDERR_CAPTURE_BYTES - sink.size();
+ if (room > 0) {
+ sink.write(buffer, 0, Math.min(read, room));
+ }
+ }
+ } catch (IOException e) {
+ log.debug("Failed to read the instance check diagnostics", e);
+ }
+ });
+ }
+
+ private static Thread startDaemon(String name, Runnable body) {
+ Thread thread = new Thread(body, name);
+ thread.setDaemon(true);
+ thread.start();
+ return thread;
+ }
+
+ private void deleteQuietly(Path checker) {
+ deleteRecursivelyQuietly(checker.getParent());
+ }
+
+ private void deleteRecursivelyQuietly(Path dir) {
+ if (!FileUtils.deleteQuietly(dir.toFile())) {
+ log.debug("Failed to clean up the instance check directory {}", dir);
+ }
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java
new file mode 100644
index 0000000000..5bb7a84d87
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java
@@ -0,0 +1,35 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo;
+import org.thingsboard.server.common.data.exception.ThingsboardException;
+
+import java.util.function.Consumer;
+
+public interface CommunityGrantService {
+
+ CommunityGrantStateInfo getStateInfo();
+
+ /** Starts or restarts the flow; a restart supersedes the previous claim token. */
+ CommunityGrantStateInfo start() throws ThingsboardException;
+
+ /**
+ * Starts an uploaded instance checker in the background on this node. The signature must verify before
+ * this returns; a refusal throws here, and the run's own outcome reaches {@link #getStateInfo()}.
+ *
+ * @param completionListener told how the run ended, on the run's own thread: {@code null} on success
+ */
+ CommunityGrantStateInfo runOfflineChecker(byte[] checkerData, byte[] signatureData, String fileName,
+ CommunityGrantCheckerInput checkerInput,
+ Consumer completionListener) throws ThingsboardException;
+
+ String getOfflineReport() throws ThingsboardException;
+
+ /** Records that the operator handed the report to the portal by hand; the flow keeps waiting. */
+ CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException;
+
+ /** Asks the portal to notify this cluster's registered owner. Throttled by a cooldown. */
+ void requestAccess() throws ThingsboardException;
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java b/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java
new file mode 100644
index 0000000000..df4f44ac23
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java
@@ -0,0 +1,527 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.community_grant;
+
+import jakarta.annotation.PreDestroy;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.thingsboard.common.util.ThingsBoardThreadFactory;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantMode;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRunStatus;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantState;
+import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo;
+import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
+import org.thingsboard.server.common.data.exception.ThingsboardException;
+import org.thingsboard.server.dao.subscription.TbClusterStore;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.security.SecureRandom;
+import java.util.Base64;
+import java.util.UUID;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Consumer;
+
+@Service
+@TbCoreComponent
+@RequiredArgsConstructor
+@Slf4j
+public class DefaultCommunityGrantService implements CommunityGrantService {
+
+ static final int CLAIM_TOKEN_BYTES = 32;
+
+ static final long REQUEST_ACCESS_COOLDOWN_MS = TimeUnit.MINUTES.toMillis(5);
+
+ static final String NOT_AVAILABLE_MESSAGE = "This action is not available on this deployment.";
+ static final String NO_CLUSTER_ID_MESSAGE =
+ "This deployment is not fully installed yet. Restart the platform and try again.";
+ private static final String START_FAILED_MESSAGE =
+ "Failed to start. Please check that the database is reachable and try again.";
+ private static final String ALREADY_FINISHED_MESSAGE = "This deployment has already completed this process.";
+ static final String UNDER_REVIEW_MESSAGE =
+ "This deployment's registration is with a reviewer. There is nothing to send again while it is.";
+ static final String REPORT_HANDED_OVER_MESSAGE =
+ "This deployment's check result has already been handed over. Starting again would abandon it.";
+ static final String NOTHING_TO_HAND_OVER_MESSAGE =
+ "This deployment is not waiting for a check result to be handed over.";
+ static final String HANDOFF_FAILED_MESSAGE =
+ "Failed to record the hand-over. Please check that the database is reachable and try again.";
+ private static final String PORTAL_MISCONFIGURED_MESSAGE =
+ "This deployment's connection to the license portal is misconfigured. Contact your administrator.";
+ static final String NO_OFFLINE_REPORT_MESSAGE = "No result is available. Run the check first.";
+ static final String OFFLINE_RUN_IN_PROGRESS_MESSAGE =
+ "A check is already running on this deployment. Wait for it to finish and try again.";
+ static final String OFFLINE_STATE_NOT_PERSISTED_MESSAGE =
+ "The check completed, but this deployment could not record it. The result is still available for download.";
+ static final String OFFLINE_RUN_START_FAILED_MESSAGE =
+ "Failed to start the check. Please check that the database is reachable and try again.";
+ static final String OFFLINE_RUN_NOT_SCHEDULED_MESSAGE =
+ "Failed to start the check: this server is shutting down. Please try again.";
+ static final String OFFLINE_RUN_INTERRUPTED_MESSAGE =
+ "The check was interrupted before it finished. Please run it again.";
+ static final String OFFLINE_RESULT_NOT_RECORDED_MESSAGE =
+ "The check completed, but this deployment could not record its result. Please check that the database "
+ + "is reachable and run the check again.";
+ static final String OFFLINE_RUN_SUPERSEDED_MESSAGE =
+ "The check finished after a newer check or enrollment replaced it, so its result was discarded.";
+ private static final String RUN_FAILED_PREFIX = "Failed to run the check. ";
+
+ /** Past the checker's own timeout: room for writing the binary and recording the result. */
+ static final long OFFLINE_RUN_GRACE_MS = TimeUnit.MINUTES.toMillis(2);
+ static final String NOT_ALREADY_REGISTERED_MESSAGE =
+ "This action is only available once this deployment is confirmed as already registered under another account.";
+ static final String REQUEST_ACCESS_RATE_LIMITED_MESSAGE =
+ "Please wait a few minutes before requesting access again.";
+ static final String REQUEST_ACCESS_STORE_FAILED_MESSAGE =
+ "Failed to process the request. Please check that the database is reachable and try again.";
+ static final String REQUEST_ACCESS_FAILED_MESSAGE =
+ "Failed to reach the license portal. Please try again later.";
+
+ @Value("${community-grant.enabled:true}")
+ private boolean enabled;
+
+ private final TbClusterStore tbClusterStore;
+ private final CommunityGrantFlowStateStore flowStateStore;
+ private final CommunityGrantPortalClient portalClient;
+ private final CommunityGrantPoller poller;
+ private final CommunityGrantReportRunner reportRunner;
+ private final CommunityGrantOfflineReportStore offlineReportStore;
+
+ private final SecureRandom secureRandom = new SecureRandom();
+ private final ReentrantLock startLock = new ReentrantLock();
+
+ /** A permit, not a lock: the request thread takes it and the executor thread gives it back. */
+ private final Semaphore offlineRunPermit = new Semaphore(1);
+
+ private ExecutorService offlineRunExecutor =
+ Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName("tb-community-grant-offline-run"));
+
+ /** A failure to read the report drops it from the answer rather than failing the whole read. */
+ @Override
+ public CommunityGrantStateInfo getStateInfo() {
+ CommunityGrantFlowState flowState = flowStateStore.get();
+ String portalUrl = portalClient.getPortalUrl();
+ CommunityGrantOfflineRun run = flowState.getOfflineRun();
+ boolean runInProgress = isOfflineRunInProgress(run, System.currentTimeMillis(), offlineRunStaleAfterMs());
+ String runError = offlineRunError(run, runInProgress);
+ String report = null;
+ if (CommunityGrantStateInfo.carriesOfflineReport(flowState)) {
+ try {
+ report = offlineReportStore.get().orElse(null);
+ } catch (Exception e) {
+ log.warn("Failed to read the stored community grant offline report", e);
+ }
+ }
+ return CommunityGrantStateInfo.of(flowState, portalUrl, report, runInProgress, runError);
+ }
+
+ @Override
+ public CommunityGrantStateInfo start() throws ThingsboardException {
+ if (!enabled) {
+ throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND);
+ }
+ startLock.lock();
+ try {
+ CommunityGrantFlowState currentState = flowStateStore.get();
+ CommunityGrantState current = currentState.getState();
+ if (current.isTerminal()) {
+ throw new ThingsboardException(ALREADY_FINISHED_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ if (current == CommunityGrantState.UNDER_REVIEW) {
+ // Re-minting would replace the token the reviewer's decision is delivered against.
+ throw new ThingsboardException(UNDER_REVIEW_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ if (current == CommunityGrantState.REPORT_HANDED_OVER) {
+ // Re-minting would abandon the submission and clear the report a failed paste comes back for.
+ throw new ThingsboardException(REPORT_HANDED_OVER_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ UUID clusterId = tbClusterStore.getClusterId()
+ .orElseThrow(() -> new ThingsboardException(NO_CLUSTER_ID_MESSAGE, ThingsboardErrorCode.GENERAL));
+
+ // Probed even when OFFLINE: the only way back to ONLINE.
+ CommunityGrantMode mode;
+ try {
+ mode = portalClient.isPortalReachable() ? CommunityGrantMode.ONLINE : CommunityGrantMode.OFFLINE;
+ } catch (IllegalArgumentException e) {
+ // Only a malformed base URL; unreachability is a plain false.
+ log.warn("Failed to reach the license portal: the configured base URL is not valid", e);
+ throw new ThingsboardException(PORTAL_MISCONFIGURED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+
+ // Only from NOT_STARTED: on a flow this deployment began, its own pending registration answers
+ // true, and the terminal ALREADY_REGISTERED would dead-end the operator's own enrollment.
+ if (mode == CommunityGrantMode.ONLINE && current == CommunityGrantState.NOT_STARTED
+ && isAlreadyRegistered(clusterId)) {
+ return enrollAsAlreadyRegistered();
+ }
+
+ String token = mintToken();
+ // Built before the token is stored, so a bad base URL leaves nothing to retire.
+ String signUpUrl;
+ try {
+ signUpUrl = portalClient.buildSignUpUrl(clusterId, token, mode);
+ } catch (Exception e) {
+ log.warn("Failed to build the sign-up URL: the configured base URL is not valid", e);
+ throw new ThingsboardException(PORTAL_MISCONFIGURED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ try {
+ tbClusterStore.saveLicenseClaimToken(token);
+ } catch (Exception e) {
+ log.warn("Failed to store the community grant claim token", e);
+ throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+
+ CommunityGrantFlowState updated;
+ try {
+ long now = System.currentTimeMillis();
+ updated = flowStateStore.update(state -> {
+ state.setMode(mode);
+ state.setState(CommunityGrantState.AWAITING_SIGNUP);
+ state.setSignUpUrl(signUpUrl);
+ state.setStartedAt(now);
+ state.setLastPolledAt(null);
+ state.setParkReason(null);
+ state.setLastOfflineCheckAt(null);
+ state.setOfflineRun(null);
+ return state;
+ });
+ } catch (Exception e) {
+ tbClusterStore.clearLicenseClaimToken(token);
+ log.warn("Failed to persist the community grant flow state after minting a token", e);
+ throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ // After the write, so a failed start keeps the previous report.
+ offlineReportStore.clear();
+ // After the write: the loop reads the persisted mode.
+ poller.arm();
+ return CommunityGrantStateInfo.of(updated, portalClient.getPortalUrl());
+ } finally {
+ startLock.unlock();
+ }
+ }
+
+ /**
+ * Refusals answer the upload request; the run itself goes to {@link #offlineRunExecutor} on this node.
+ * One run at a time: per node by {@link #offlineRunPermit}, cluster-wide by the run record on the flow
+ * state. Two nodes starting in the same instant can both pass; the run written last keeps its result.
+ */
+ @Override
+ public CommunityGrantStateInfo runOfflineChecker(byte[] checkerData, byte[] signatureData, String fileName,
+ CommunityGrantCheckerInput checkerInput,
+ Consumer completionListener)
+ throws ThingsboardException {
+ if (!enabled) {
+ throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND);
+ }
+ if (!offlineRunPermit.tryAcquire()) {
+ throw new ThingsboardException(OFFLINE_RUN_IN_PROGRESS_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS);
+ }
+ boolean handedToExecutor = false;
+ try {
+ try {
+ reportRunner.verifyUploadedChecker(checkerData, signatureData, fileName);
+ } catch (IllegalArgumentException e) {
+ throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ } catch (Exception e) {
+ log.warn("Failed to verify the uploaded instance check", e);
+ throw new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL);
+ }
+ UUID runId = UUID.randomUUID();
+ long startedAt = System.currentTimeMillis();
+ CommunityGrantStateInfo answer = CommunityGrantStateInfo.of(recordOfflineRunStarted(runId, startedAt),
+ portalClient.getPortalUrl(), null, true, null);
+ try {
+ offlineRunExecutor.execute(() ->
+ completeOfflineRun(runId, checkerData, signatureData, fileName, checkerInput,
+ completionListener));
+ } catch (RejectedExecutionException e) {
+ log.warn("Failed to schedule the uploaded instance check", e);
+ recordOfflineRunFailed(runId, OFFLINE_RUN_NOT_SCHEDULED_MESSAGE);
+ throw new ThingsboardException(OFFLINE_RUN_NOT_SCHEDULED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ handedToExecutor = true;
+ return answer;
+ } finally {
+ if (!handedToExecutor) {
+ offlineRunPermit.release();
+ }
+ }
+ }
+
+ private CommunityGrantFlowState recordOfflineRunStarted(UUID runId, long startedAt) throws ThingsboardException {
+ long staleAfterMs = offlineRunStaleAfterMs();
+ try {
+ return flowStateStore.update(state -> {
+ if (isOfflineRunInProgress(state.getOfflineRun(), startedAt, staleAfterMs)) {
+ throw new UpdateRefusal(OFFLINE_RUN_IN_PROGRESS_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS);
+ }
+ state.setOfflineRun(CommunityGrantOfflineRun.running(runId, startedAt));
+ return state;
+ });
+ } catch (UpdateRefusal e) {
+ throw new ThingsboardException(e.getMessage(), e.errorCode);
+ } catch (Exception e) {
+ // No cause: the audit log stores the full stack trace.
+ log.warn("Failed to record the start of a community grant offline check", e);
+ throw new ThingsboardException(OFFLINE_RUN_START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ }
+
+ private void completeOfflineRun(UUID runId, byte[] checkerData, byte[] signatureData, String fileName,
+ CommunityGrantCheckerInput checkerInput, Consumer completionListener) {
+ try {
+ ThingsboardException failure = null;
+ try {
+ runAndRecordOfflineCheck(runId, checkerData, signatureData, fileName, checkerInput);
+ } catch (ThingsboardException e) {
+ failure = e;
+ } catch (Exception e) {
+ log.warn("Failed to complete the uploaded instance check", e);
+ failure = new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL);
+ }
+ if (failure != null) {
+ recordOfflineRunFailed(runId, failure.getMessage());
+ }
+ try {
+ completionListener.accept(failure);
+ } catch (Exception e) {
+ log.warn("Failed to report the end of a community grant offline check", e);
+ }
+ } finally {
+ offlineRunPermit.release();
+ }
+ }
+
+ private void runAndRecordOfflineCheck(UUID runId, byte[] checkerData, byte[] signatureData, String fileName,
+ CommunityGrantCheckerInput checkerInput) throws ThingsboardException {
+ String report;
+ try {
+ report = reportRunner.runUploadedChecker(checkerData, signatureData, fileName, checkerInput);
+ } catch (IllegalArgumentException e) {
+ throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ } catch (Exception e) {
+ log.warn("Failed to run the uploaded instance check", e);
+ throw new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL);
+ }
+ CommunityGrantOfflineRun current;
+ try {
+ current = flowStateStore.get().getOfflineRun();
+ } catch (Exception e) {
+ log.warn("Failed to read the community grant flow state after an offline check", e);
+ throw new ThingsboardException(OFFLINE_RESULT_NOT_RECORDED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ if (current == null || !current.isOwnedBy(runId)) {
+ throw supersededOfflineRun();
+ }
+ // Before and apart from the state write: OFFLINE_STATE_NOT_PERSISTED_MESSAGE promises the download.
+ offlineReportStore.put(report);
+ long lastOfflineCheckAt = System.currentTimeMillis();
+ AtomicBoolean owned = new AtomicBoolean();
+ try {
+ flowStateStore.update(state -> {
+ owned.set(state.getOfflineRun() != null && state.getOfflineRun().isOwnedBy(runId));
+ if (!owned.get()) {
+ return state;
+ }
+ if (state.getMode() != CommunityGrantMode.ONLINE) {
+ state.setMode(CommunityGrantMode.OFFLINE);
+ }
+ if (!state.getState().isAwaitingOrPastDecision()) {
+ state.setState(CommunityGrantState.VALIDATING);
+ state.setParkReason(null);
+ }
+ state.setLastOfflineCheckAt(lastOfflineCheckAt);
+ state.setOfflineRun(null);
+ return state;
+ });
+ } catch (Exception e) {
+ log.warn("Failed to persist the community grant flow state after a successful offline check", e);
+ throw new ThingsboardException(OFFLINE_STATE_NOT_PERSISTED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ if (!owned.get()) {
+ // The report stays: deleting it could delete a newer run's.
+ throw supersededOfflineRun();
+ }
+ }
+
+ private static ThingsboardException supersededOfflineRun() {
+ return new ThingsboardException(OFFLINE_RUN_SUPERSEDED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+
+ /** Best effort: a run left {@code RUNNING} is reported as interrupted once it goes stale. */
+ private void recordOfflineRunFailed(UUID runId, String error) {
+ try {
+ flowStateStore.update(state -> {
+ CommunityGrantOfflineRun run = state.getOfflineRun();
+ if (run != null && run.isOwnedBy(runId)) {
+ run.setStatus(CommunityGrantOfflineRunStatus.FAILED);
+ run.setError(error);
+ }
+ return state;
+ });
+ } catch (Exception e) {
+ log.warn("Failed to record a failed community grant offline check", e);
+ }
+ }
+
+ private long offlineRunStaleAfterMs() {
+ return TimeUnit.SECONDS.toMillis(reportRunner.getCheckerTimeoutSec()) + OFFLINE_RUN_GRACE_MS;
+ }
+
+ private static boolean isOfflineRunInProgress(CommunityGrantOfflineRun run, long now, long staleAfterMs) {
+ return run != null && run.getStatus() == CommunityGrantOfflineRunStatus.RUNNING
+ && run.getStartedAt() != null && now - run.getStartedAt() <= staleAfterMs;
+ }
+
+ private static String offlineRunError(CommunityGrantOfflineRun run, boolean inProgress) {
+ if (run == null || inProgress) {
+ return null;
+ }
+ return run.getStatus() == CommunityGrantOfflineRunStatus.FAILED
+ ? run.getError()
+ : OFFLINE_RUN_INTERRUPTED_MESSAGE;
+ }
+
+ @PreDestroy
+ public void stop() {
+ offlineRunExecutor.shutdownNow();
+ }
+
+ @Override
+ public String getOfflineReport() throws ThingsboardException {
+ return offlineReportStore.get()
+ .orElseThrow(() -> new ThingsboardException(NO_OFFLINE_REPORT_MESSAGE,
+ ThingsboardErrorCode.ITEM_NOT_FOUND));
+ }
+
+ /** Under {@link #startLock}, so a concurrent start() is not relabelled as handed over. */
+ @Override
+ public CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException {
+ if (!enabled) {
+ throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND);
+ }
+ startLock.lock();
+ try {
+ CommunityGrantState current = flowStateStore.get().getState();
+ if (current == CommunityGrantState.REPORT_HANDED_OVER) {
+ return getStateInfo();
+ }
+ if (current != CommunityGrantState.VALIDATING) {
+ throw new ThingsboardException(NOTHING_TO_HAND_OVER_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ try {
+ flowStateStore.update(state -> {
+ // Re-tested: a poll may have retired the flow since the read above.
+ if (state.getState() == CommunityGrantState.VALIDATING) {
+ state.setState(CommunityGrantState.REPORT_HANDED_OVER);
+ }
+ return state;
+ });
+ } catch (Exception e) {
+ log.warn("Failed to persist the community grant offline hand-off", e);
+ throw new ThingsboardException(HANDOFF_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ return getStateInfo();
+ } finally {
+ startLock.unlock();
+ }
+ }
+
+ @Override
+ public void requestAccess() throws ThingsboardException {
+ if (!enabled) {
+ throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND);
+ }
+ UUID clusterId;
+ long now = System.currentTimeMillis();
+ try {
+ clusterId = tbClusterStore.getClusterId().orElse(null);
+ // The cooldown lives on the shared flow state; only the lock is per node.
+ flowStateStore.update(state -> {
+ // Not WRONG_INSTALLATION: there is no registration on this cluster id to notify.
+ if (state.getState() != CommunityGrantState.ALREADY_REGISTERED) {
+ throw new UpdateRefusal(NOT_ALREADY_REGISTERED_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ Long lastRequestAccessAt = state.getLastRequestAccessAt();
+ if (lastRequestAccessAt != null && now - lastRequestAccessAt < REQUEST_ACCESS_COOLDOWN_MS) {
+ throw new UpdateRefusal(REQUEST_ACCESS_RATE_LIMITED_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS);
+ }
+ if (clusterId == null) {
+ throw new UpdateRefusal(NO_CLUSTER_ID_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ // Recorded whatever the portal call below does.
+ state.setLastRequestAccessAt(now);
+ return state;
+ });
+ } catch (UpdateRefusal e) {
+ throw new ThingsboardException(e.getMessage(), e.errorCode);
+ } catch (Exception e) {
+ log.warn("Failed to read or persist the community grant request-access state", e);
+ throw new ThingsboardException(REQUEST_ACCESS_STORE_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ try {
+ portalClient.requestAccess(clusterId);
+ } catch (Exception e) {
+ log.warn("Failed to ask the license portal to notify the registered owner", e);
+ throw new ThingsboardException(REQUEST_ACCESS_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ }
+
+ /** Unchecked so it can leave an updater; translated back to {@link ThingsboardException} by the caller. */
+ private static final class UpdateRefusal extends RuntimeException {
+ private final ThingsboardErrorCode errorCode;
+
+ private UpdateRefusal(String message, ThingsboardErrorCode errorCode) {
+ super(message);
+ this.errorCode = errorCode;
+ }
+ }
+
+ /** The token is retired before the terminal state is written, since nothing retires it afterwards. */
+ private CommunityGrantStateInfo enrollAsAlreadyRegistered() throws ThingsboardException {
+ poller.disarm();
+ tbClusterStore.forceClearLicenseClaimToken();
+ try {
+ CommunityGrantFlowState updated = flowStateStore.update(state -> {
+ state.setMode(CommunityGrantMode.ONLINE);
+ state.setState(CommunityGrantState.ALREADY_REGISTERED);
+ state.clearClaim();
+ state.setLastPolledAt(null);
+ state.setParkReason(null);
+ state.setOfflineRun(null);
+ return state;
+ });
+ offlineReportStore.clear();
+ return CommunityGrantStateInfo.of(updated, portalClient.getPortalUrl());
+ } catch (Exception e) {
+ log.warn("Failed to persist the community grant flow state for an already-registered deployment", e);
+ throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL);
+ }
+ }
+
+ /** Best effort: a failure here reads as not registered, and the poll reaches the same answer later. */
+ private boolean isAlreadyRegistered(UUID clusterId) {
+ try {
+ return portalClient.isAlreadyRegistered(clusterId);
+ } catch (Exception e) {
+ log.debug("Failed to read the cluster status from the portal", e);
+ return false;
+ }
+ }
+
+ private String mintToken() {
+ byte[] tokenBytes = new byte[CLAIM_TOKEN_BYTES];
+ secureRandom.nextBytes(tokenBytes);
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
index 1564ad8e7b..87f9f4ec1d 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
@@ -47,6 +47,7 @@ import org.thingsboard.server.dao.widget.WidgetsBundleService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.edge.rpc.EdgeEventStorageSettings;
import org.thingsboard.server.service.edge.rpc.EdgeRpcService;
+import org.thingsboard.server.service.rpc.TbRpcService;
import org.thingsboard.server.service.edge.rpc.processor.EdgeProcessor;
import org.thingsboard.server.service.edge.rpc.processor.ai.AiModelProcessor;
import org.thingsboard.server.service.edge.rpc.processor.apikey.ApiKeyProcessor;
@@ -130,6 +131,9 @@ public class EdgeContextComponent {
@Autowired
private DeviceService deviceService;
+ @Autowired
+ private TbRpcService tbRpcService;
+
@Autowired
private DomainService domainService;
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
index 129ff896f2..b2b8f37c0a 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
@@ -326,20 +326,23 @@ public class EdgeMsgConstructorUtils {
responseBuilder.setResponse(body.get("response").asText());
}
builder.setResponseMsg(responseBuilder.build());
- } else {
+ } else if (body.has("method")) {
RpcRequestMsg.Builder requestBuilder = RpcRequestMsg.newBuilder();
requestBuilder.setMethod(body.get("method").asText());
requestBuilder.setParams(body.get("params").asText());
builder.setRequestMsg(requestBuilder.build());
}
+ // else: status-only message (rpcStatus set in constructDeviceRpcMsg) carries neither request nor response body
return builder.build();
}
private static DeviceRpcCallMsg.Builder constructDeviceRpcMsg(UUID deviceId, JsonNode body) {
DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder()
.setDeviceIdMSB(deviceId.getMostSignificantBits())
- .setDeviceIdLSB(deviceId.getLeastSignificantBits())
- .setRequestId(body.get("requestId").asInt());
+ .setDeviceIdLSB(deviceId.getLeastSignificantBits());
+ if (body.get("requestId") != null) {
+ builder.setRequestId(body.get("requestId").asInt());
+ }
if (body.get("oneway") != null) {
builder.setOneway(body.get("oneway").asBoolean());
}
@@ -366,6 +369,9 @@ public class EdgeMsgConstructorUtils {
if (body.get("sessionId") != null) {
builder.setSessionId(body.get("sessionId").asText());
}
+ if (body.get("rpcStatus") != null) {
+ builder.setRpcStatus(body.get("rpcStatus").asText());
+ }
return builder;
}
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
index b14fa32a38..ba80a4cf2b 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
@@ -74,9 +74,11 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
+import java.util.function.Predicate;
import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE;
import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME;
@@ -306,13 +308,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
@Override
public void deleteEdge(TenantId tenantId, EdgeId edgeId) {
- EdgeGrpcSession session = sessions.get(edgeId);
- if (session != null && session.isConnected()) {
+ EdgeGrpcSession toRemove = detachSession(edgeId);
+ if (toRemove != null) {
log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId);
- destroySession(session);
- session.cleanUp();
- sessions.remove(edgeId);
- sessionsById.remove(session.getSessionId());
+ sessionsById.remove(toRemove.getSessionId());
final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock());
newEventLock.lock();
try {
@@ -320,7 +319,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
} finally {
newEventLock.unlock();
}
- cancelScheduleEdgeEventsCheck(edgeId);
+ destroySession(toRemove);
+ toRemove.cleanUp();
}
cancelPendingDisconnectNotification(edgeId);
}
@@ -362,16 +362,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
Edge edge = edgeGrpcSession.getEdge();
TenantId tenantId = edge.getTenantId();
log.info("[{}][{}] edge [{}] connected successfully.", tenantId, edgeGrpcSession.getSessionId(), edgeId);
- if (sessions.containsKey(edgeId)) {
- EdgeGrpcSession existing = sessions.get(edgeId);
- if (existing != null) {
- log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), existing.getSessionId(), edgeId);
- destroySession(existing);
- sessionsById.remove(existing.getSessionId());
- }
- }
- sessions.put(edgeId, edgeGrpcSession);
+ EdgeGrpcSession replaced = attachSession(edgeId, edgeGrpcSession);
sessionsById.put(edgeGrpcSession.getSessionId(), edgeGrpcSession);
+ if (replaced != null) {
+ log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), replaced.getSessionId(), edgeId);
+ sessionsById.remove(replaced.getSessionId());
+ }
final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock());
newEventLock.lock();
try {
@@ -392,9 +388,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
// Connect notifies immediately; only the disconnect notification is debounced (see scheduleDisconnectNotification).
pushStateEventToRuleEngine(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT);
notifyEdgeConnectivity(edge, true);
- cancelScheduleEdgeEventsCheck(edgeId);
edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE);
scheduleEdgeEventsCheck(edgeGrpcSession);
+ if (replaced != null) {
+ destroySession(replaced);
+ }
}
private void startSyncProcess(TenantId tenantId, EdgeId edgeId, UUID requestId, String requestServiceId) {
@@ -456,54 +454,73 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
EdgeId edgeId = session.getEdge().getId();
TenantId tenantId = session.getEdge().getTenantId();
- cancelScheduleEdgeEventsCheck(edgeId);
+ // arm the next check only while this exact session is still the current one, atomically with
+ // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the
+ // re-arm nor cancel a check that belongs to a session other than the one it is tearing down
+ sessions.compute(edgeId, (id, current) -> {
+ if (current != session) {
+ log.debug("[{}] Session is not current anymore and edge event check schedule must not be started [{}]",
+ tenantId, edgeId.getId());
+ return current;
+ }
+ cancelScheduleEdgeEventsCheck(edgeId);
+ sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule(
+ () -> processEvents(session, edgeId, tenantId),
+ ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS));
+ log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId());
+ return current;
+ });
+ }
- if (sessions.containsKey(edgeId)) {
- ScheduledFuture> edgeEventCheckTask = edgeEventProcessingExecutorService.schedule(() -> {
- try {
- final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock());
- newEventLock.lock();
- try {
- if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) {
- log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId());
- sessionNewEvents.put(edgeId, false);
- session.processHighPriorityEvents();
- processEdgeEventMigrationIfNeeded(session, edgeId);
- if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) {
- Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() {
- @Override
- public void onSuccess(Boolean newEventsAdded) {
- if (Boolean.TRUE.equals(newEventsAdded)) {
- log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId());
- sessionNewEvents.put(edgeId, true);
- }
- scheduleEdgeEventsCheck(session);
+ private void processEvents(EdgeGrpcSession session, EdgeId edgeId, TenantId tenantId) {
+ try {
+ final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock());
+ newEventLock.lock();
+ try {
+ if (sessions.get(edgeId) != session) {
+ log.debug("[{}] Session is not current anymore, edge event check must not run for edge [{}]",
+ tenantId, edgeId.getId());
+ return;
+ }
+ if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) {
+ log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId());
+ sessionNewEvents.put(edgeId, false);
+ session.processHighPriorityEvents();
+ processEdgeEventMigrationIfNeeded(session, edgeId);
+ if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) {
+ Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() {
+ @Override
+ public void onSuccess(Boolean newEventsAdded) {
+ if (Boolean.TRUE.equals(newEventsAdded)) {
+ log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId());
+ final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock());
+ newEventLock.lock();
+ try {
+ sessionNewEvents.put(edgeId, true);
+ } finally {
+ newEventLock.unlock();
}
+ }
+ scheduleEdgeEventsCheck(session);
+ }
- @Override
- public void onFailure(Throwable t) {
- log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t);
- scheduleEdgeEventsCheck(session);
- }
- }, ctx.getGrpcCallbackExecutorService());
- } else {
+ @Override
+ public void onFailure(Throwable t) {
+ log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t);
scheduleEdgeEventsCheck(session);
}
- } else {
- scheduleEdgeEventsCheck(session);
- }
- } finally {
- newEventLock.unlock();
+ }, ctx.getGrpcCallbackExecutorService());
+ } else {
+ scheduleEdgeEventsCheck(session);
}
- } catch (Exception e) {
- log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e);
+ } else {
+ scheduleEdgeEventsCheck(session);
}
- }, ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS);
- sessionEdgeEventChecks.put(edgeId, edgeEventCheckTask);
- log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId());
- } else {
- log.debug("[{}] Session was removed and edge event check schedule must not be started [{}]",
- tenantId, edgeId.getId());
+ } finally {
+ newEventLock.unlock();
+ }
+ } catch (Exception e) {
+ log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e);
}
}
@@ -531,58 +548,26 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
private void onEdgeDisconnect(Edge edge, UUID sessionId) {
EdgeId edgeId = edge.getId();
log.info("[{}][{}] edge disconnected!", edgeId, sessionId);
- EdgeGrpcSession current = sessions.get(edgeId);
- // Claim-once removal: get() and remove() are not atomic, so a session that was replaced between the
- // two would otherwise be dropped from the map, torn down and marked inactive by this stale callback
- // even though it is the live one. Losing the race means this callback owns nothing - fall through to
- // the stale-session branch below.
- if (current != null && current.getSessionId().equals(sessionId) && sessions.remove(edgeId, current)) {
- EdgeGrpcSession toRemove = current;
- final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock());
- newEventLock.lock();
- try {
- sessionNewEvents.remove(edgeId);
- } finally {
- newEventLock.unlock();
- }
- destroySession(toRemove);
+ EdgeGrpcSession toRemove = detachSession(edgeId, current -> current.getSessionId().equals(sessionId));
+ if (toRemove != null) {
+ // sessionNewEvents is deliberately left as is: clearing it here could wipe the flag a
+ // reconnecting session has just set, and updateSessionEventsFlag only lifts FALSE, not a
+ // missing entry, which would leave the check loop idle forever. deleteEdge still clears it
sessionsById.remove(sessionId);
TenantId tenantId = toRemove.getEdge().getTenantId();
- // The edge may already have been claimed by a newer session - on this node (a replacement that
- // landed while this stale callback was tearing its own session down) or on another live node.
- // Either way the edge is connected, so none of the disconnect side effects apply:
- // - clearing the flag makes saveEdgeEvent drop assignment events until a full sync;
- // - a newer lastDisconnectTime would contradict the live session's lastConnectTime;
- // - the DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE in the metadata,
- // so a rule chain wiring Disconnect Event -> Save Attributes writes active=false straight
- // back, re-creating the dropped-event behaviour through the rule engine;
- // - the user-facing 'edge disconnected' notification would contradict a live session.
- // Ownership being unknown (no cache entry) still counts as disconnected, so a genuinely offline
- // edge is always marked inactive.
- boolean replacedOnThisNode = sessions.containsKey(edgeId);
- if (!replacedOnThisNode && !isOwnedByAnotherNode(edgeId)) {
+ // A newer session may already own the edge, on this node or on another live one. In that case the edge
+ // is connected, so skip all disconnect side effects: active=false, lastDisconnectTime, DISCONNECT_EVENT
+ // (its payload can write active=false back via Save Attributes) and the disconnect notification.
+ // Unknown ownership (no cache entry) still counts as disconnected. The local map is read last, after
+ // the cache round-trip, to see a same-node replacement as late as possible.
+ if (!isOwnedByAnotherNode(edgeId) && !sessions.containsKey(edgeId)) {
save(tenantId, edgeId, ACTIVITY_STATE, false);
long lastDisconnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs);
- pushStateEventToRuleEngine(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
- // Inside the guard, not after it. fireDelayedDisconnectNotification does re-verify liveness,
- // but only on the debounced path: with EDGES_DISCONNECT_NOTIFICATION_DELAY_MS=0
- // scheduleDisconnectNotification notifies straight away and skips that re-verify, so a live
- // replacement would still raise a false 'edge disconnected'. The guard above has already
- // answered the same question, so use it. On the debounced path this only saves a task that
- // would have re-verified and dropped the notification anyway.
+ pushStateEventToRuleEngine(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
scheduleDisconnectNotification(edge);
}
- // sessionEdgeEventChecks is keyed by edgeId, not by session, so a replacement that landed on this
- // node while this stale callback was running has already scheduled its check under the same key.
- // Cancelling it here would leave the live session with no check loop - the loop only reschedules
- // itself from inside the task, so a cancelled task never runs again - and downlinks, the migration
- // check and high-priority events would stall silently until the edge reconnects. When the edge is
- // owned by another node there is nothing live to protect: the check is node-local and belongs to
- // the session we just tore down.
- if (!replacedOnThisNode) {
- cancelScheduleEdgeEventsCheck(edgeId);
- }
+ destroySession(toRemove);
} else {
log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId);
EdgeGrpcSession stale = sessionsById.remove(sessionId);
@@ -605,6 +590,53 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
}
}
+ /**
+ * Registers the session as the current one for the edge and cancels the edge event check armed by
+ * the session it replaces, as a single atomic step. Returns the replaced session, or null if there
+ * was none - the caller is responsible for destroying it outside of this critical section.
+ *
+ * Only cheap non-blocking work may run inside the remapping function: it holds the bin lock of
+ * {@link #sessions} for this edge, so everything slow or lock-taking - {@link #destroySession},
+ * {@code EdgeGrpcSession.cleanUp()}, {@code save(...)}, {@code pushRuleEngineMessage(...)} or
+ * acquiring the per-edge new events lock - has to be done by the caller once compute has returned.
+ */
+ private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) {
+ AtomicReference replaced = new AtomicReference<>();
+ sessions.compute(edgeId, (id, current) -> {
+ replaced.set(current);
+ cancelScheduleEdgeEventsCheck(edgeId);
+ return session;
+ });
+ return replaced.get();
+ }
+
+ private EdgeGrpcSession detachSession(EdgeId edgeId) {
+ return detachSession(edgeId, s -> true);
+ }
+
+ /**
+ * Detaches the edge's registered session and cancels its edge event check as a single atomic step,
+ * but only if that session satisfies shouldDetach. Returns the detached session, or null if the
+ * predicate rejected it - most importantly when another session has taken the edge over in the
+ * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose
+ * the check it has just armed. The caller destroys the returned session outside the atomic step.
+ *
+ * The remapping function is subject to the same "cheap non-blocking work only" rule as
+ * {@link #attachSession(EdgeId, EdgeGrpcSession)}.
+ */
+ private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) {
+ AtomicReference detached = new AtomicReference<>();
+ sessions.compute(edgeId, (id, current) -> {
+ if (current == null || !shouldDetach.test(current)) {
+ return current;
+ }
+ detached.set(current);
+ cancelScheduleEdgeEventsCheck(edgeId);
+ return null;
+ });
+ return detached.get();
+ }
+
// Only evict if the cache still points to this node. If the edge already reconnected to a different
// TB-Core node within the keep-alive window, that node has overwritten the entry - evicting it here
// would wipe the live owner and make fireDelayedDisconnectNotification raise a false 'disconnected'.
@@ -627,11 +659,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
// - entry naming a node that is no longer in the cluster: the edge sessions cache has no TTL by default
// (CACHE_SPECS_EDGE_SESSIONS_TTL=0) and is only ever evicted by the owning node, so a node that died
// without evicting would otherwise keep the edge marked active forever, with no reconciler to correct it.
- // Note this covers a node that is gone, not one that restarted under the same service id - that claim
- // still resolves as live, leaving the edge marked active until something reconnects. That errs towards
- // queueing edge events rather than dropping them, which is the safe direction.
- // This narrows the race rather than closing it: the attribute is plain last-writer-wins, and two nodes can
- // still issue their async writes in an order this read cannot see.
private boolean isOwnedByAnotherNode(EdgeId edgeId) {
TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId);
if (wrapper == null) {
@@ -649,6 +676,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
return edgeIdServiceIdCache.get(edgeId) != null;
}
+ /**
+ * Stops the session's edge event consumer and shuts down its executor, collecting the session for a
+ * later retry if that fails. This can block for seconds - {@code KafkaEdgeGrpcSession.destroy()}
+ * gives the consumer executor up to 5s to terminate - so it must never be called from inside a
+ * {@link #sessions} remapping function.
+ */
private void destroySession(EdgeGrpcSession session) {
try (session) {
if (!session.destroy()) {
@@ -863,10 +896,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
private void cleanupZombieSessions() {
try {
- // Compare-and-remove: destroy() above is not instantaneous, so the edge may have reconnected and
- // put a live session under this id in the meantime. Removing it unconditionally would leave a
- // connected edge with no entry in 'sessions', silently no-opping every downlink lookup.
- tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s));
+ // detach by identity: the edge may have reconnected since the zombie scan, and that newer
+ // session must neither be evicted nor have its edge event check cancelled by the cleanup of
+ // the one it replaced
+ tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> detachSession(s.getEdge().getId(), current -> current == s));
tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId()));
zombieSessions.removeIf(zombie -> {
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
index b0db4d7f2d..75e0c22a73 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
@@ -9,6 +9,7 @@ import com.google.common.util.concurrent.SettableFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.databind.JsonNode;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.Device;
@@ -24,7 +25,10 @@ import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.msg.TbMsgType;
+import org.thingsboard.server.common.data.id.RpcId;
+import org.thingsboard.server.common.data.rpc.Rpc;
import org.thingsboard.server.common.data.rpc.RpcError;
+import org.thingsboard.server.common.data.rpc.RpcStatus;
import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgDataType;
@@ -116,7 +120,10 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
@Override
public ListenableFuture processDeviceRpcCallFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) {
log.trace("[{}] processDeviceRpcCallFromEdge [{}]", tenantId, deviceRpcCallMsg);
- if (deviceRpcCallMsg.hasResponseMsg()) {
+ if (deviceRpcCallMsg.hasRpcStatus()) {
+ // RPC v2 (persistent) status update from the edge - update the cloud Rpc entity (same id == request UUID).
+ return processDeviceRpcStatusFromEdge(tenantId, edge, deviceRpcCallMsg);
+ } else if (deviceRpcCallMsg.hasResponseMsg()) {
return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg);
} else if (deviceRpcCallMsg.hasRequestMsg()) {
return processDeviceRpcRequestFromEdge(tenantId, edge, deviceRpcCallMsg);
@@ -124,6 +131,46 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
return Futures.immediateFuture(null);
}
+ private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) {
+ RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB()));
+ Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId);
+ if (existingRpc == null) {
+ // RPC is unknown to the cloud (edge-originated or already deleted) - nothing to sync
+ log.debug("[{}][{}] Ignoring RPC status [{}] from edge - RPC not found", tenantId, rpcId, deviceRpcCallMsg.getRpcStatus());
+ return Futures.immediateFuture(null);
+ }
+ if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) {
+ // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy.
+ // Mark the edge-sync context so TbRpcService.deleteRpc does not echo the delete back to edges.
+ try {
+ edgeSynchronizationManager.getEdgeId().set(edge.getId());
+ edgeCtx.getTbRpcService().deleteRpc(tenantId, existingRpc);
+ } finally {
+ edgeSynchronizationManager.getEdgeId().remove();
+ }
+ return Futures.immediateFuture(null);
+ }
+ RpcStatus rpcStatus = RpcStatus.valueOf(deviceRpcCallMsg.getRpcStatus());
+ if (!existingRpc.getStatus().isIntermediate() && existingRpc.getStatus() != RpcStatus.TIMEOUT && rpcStatus.isIntermediate()) {
+ // guard against a final RPC regressing to an intermediate status (e.g. stale DELIVERED after SUCCESSFUL).
+ // TIMEOUT is not final - the device actor retries the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED).
+ log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already final [{}]",
+ tenantId, rpcId, rpcStatus, existingRpc.getStatus());
+ return Futures.immediateFuture(null);
+ }
+ JsonNode response = null;
+ if (deviceRpcCallMsg.hasResponseMsg() && !StringUtils.isEmpty(deviceRpcCallMsg.getResponseMsg().getResponse())) {
+ String payload = deviceRpcCallMsg.getResponseMsg().getResponse();
+ try {
+ response = JacksonUtil.toJsonNode(payload);
+ } catch (IllegalArgumentException e) {
+ response = JacksonUtil.newObjectNode().put("error", payload);
+ }
+ }
+ edgeCtx.getTbRpcService().save(tenantId, rpcId, rpcStatus, response);
+ return Futures.immediateFuture(null);
+ }
+
private ListenableFuture processDeviceRpcResponseFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) {
SettableFuture futureToSet = SettableFuture.create();
UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB());
diff --git a/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java b/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java
index 24bdadd2d5..b3a46fd60f 100644
--- a/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java
+++ b/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java
@@ -8,4 +8,6 @@ public interface EntityDatabaseSchemaService extends DatabaseSchemaService {
void createOrUpdateViewsAndFunctions() throws Exception;
+ void generateClusterIdIfNotExist();
+
}
diff --git a/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java b/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java
index 8ed65c390f..e90df5e1ea 100644
--- a/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java
+++ b/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java
@@ -6,6 +6,14 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.UUID;
+
@Service
@Profile("install")
@Slf4j
@@ -43,4 +51,36 @@ public class SqlEntityDatabaseSchemaService extends SqlAbstractDatabaseSchemaSer
executeQueryFromFile(SCHEMA_FUNCTIONS_SQL);
}
+ @Override
+ public void generateClusterIdIfNotExist() {
+ var clusterId = UUID.randomUUID();
+ try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
+ PreparedStatement statement = conn.prepareStatement(
+ "INSERT INTO tb_cluster (cluster_id) SELECT ?::uuid WHERE NOT EXISTS (SELECT 1 FROM tb_cluster) ON CONFLICT DO NOTHING")) {
+ statement.setString(1, clusterId.toString());
+ int insertedRows = statement.executeUpdate();
+ UUID storedClusterId = insertedRows > 0 ? clusterId : readClusterId(conn);
+ if (storedClusterId != null) {
+ logClusterId(storedClusterId);
+ }
+ } catch (SQLException e) {
+ log.error("Failed to generate Cluster id", e);
+ throw new RuntimeException("Failed to generate Cluster id", e);
+ }
+ }
+
+ private UUID readClusterId(Connection conn) throws SQLException {
+ try (Statement statement = conn.createStatement();
+ ResultSet rs = statement.executeQuery("SELECT cluster_id FROM tb_cluster")) {
+ return rs.next() ? rs.getObject(1, UUID.class) : null;
+ }
+ }
+
+ private void logClusterId(UUID clusterId) {
+ String line = ":: Cluster Id: " + clusterId + " ::";
+ String border = "=".repeat(line.length());
+ // Logged at JVM shutdown so it follows the rest of the install output.
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> log.info("\n{}\n{}\n{}\n", border, line, border)));
+ }
+
}
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/LtsMigrationService.java
index 9f6e22b2b3..d333814171 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/LtsMigrationService.java
@@ -67,18 +67,29 @@ public class LtsMigrationService {
.toList();
}
- /** No-downtime path: per migration in (from, to] run SQL, then apply(), then record the version. */
- public void applyMigrations(String fromVersion, String toVersion) {
- for (VersionedMigration vm : select(fromVersion, toVersion)) {
- LtsMigration migration = vm.migration();
+ /**
+ * No version in (from, to] is recorded until every migration and {@code afterSchemaPhase} succeed, so a
+ * failure re-runs them all: each {@link LtsMigration} and its SQL must be idempotent.
+ */
+ public void applyMigrations(String fromVersion, String toVersion, Runnable afterSchemaPhase) {
+ List selected = select(fromVersion, toVersion);
+ for (VersionedMigration versionedMigration : selected) {
+ LtsMigration migration = versionedMigration.migration();
String version = migration.getVersion();
transactionTemplate.executeWithoutResult(status -> {
runSchemaUpdate(version);
migration.apply();
- schemaSettingsService.updateSchemaVersion(version);
});
log.info("Applied LTS migration {}", version);
}
+
+ afterSchemaPhase.run();
+
+ for (VersionedMigration versionedMigration : selected) {
+ String version = versionedMigration.migration().getVersion();
+ schemaSettingsService.updateSchemaVersion(version);
+ log.info("Recorded LTS migration version {}", version);
+ }
}
/** Offline major-upgrade schema phase: per migration in (from, to] run SQL only. No version record. */
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
new file mode 100644
index 0000000000..2a28cce7af
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java
@@ -0,0 +1,43 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.install.lts;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Component;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+import java.util.UUID;
+
+/**
+ * Creates {@code tb_cluster} and mints the cluster id on the no-downtime patch path, which runs neither
+ * {@code schema-entities.sql} nor {@code generateClusterIdIfNotExist()}. Both steps are idempotent.
+ */
+@Slf4j
+@Component
+@TbCoreComponent
+@RequiredArgsConstructor
+public class V4_3_1_6Migration implements LtsMigration {
+
+ private final JdbcTemplate jdbcTemplate;
+
+ @Override
+ public String getVersion() {
+ return "4.3.1.6";
+ }
+
+ // Must run in the migration transaction: tb_cluster is created there and is not yet visible to other connections.
+ @Override
+ public void apply() {
+ UUID clusterId = UUID.randomUUID();
+ int insertedRows = jdbcTemplate.update(
+ "INSERT INTO tb_cluster (cluster_id) SELECT ?::uuid WHERE NOT EXISTS (SELECT 1 FROM tb_cluster) ON CONFLICT DO NOTHING",
+ clusterId.toString());
+ if (insertedRows > 0) {
+ log.info("Generated Cluster Id: {}", clusterId);
+ } else {
+ log.info("Cluster Id already exists, keeping it");
+ }
+ }
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
index bb57ceab5d..2fd3425ed0 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
@@ -7,9 +7,9 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
+import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.asset.AssetProfile;
-import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
@@ -25,7 +25,6 @@ import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor;
-import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor;
@@ -82,7 +81,6 @@ public class DefaultIotHubService implements IotHubService {
private static final String SECTION_RULE_CHAIN_METADATA = "rule chain metadata";
private static final String ITEM_TYPE_WIDGET = "widget";
- private static final String ITEM_TYPE_DASHBOARD = "dashboard";
private static final String ITEM_TYPE_CALCULATED_FIELD = "calculated field";
private static final String ITEM_TYPE_ALARM_RULE = "alarm rule";
private static final String ITEM_TYPE_RULE_CHAIN = "rule chain";
@@ -157,7 +155,6 @@ public class DefaultIotHubService implements IotHubService {
IotHubInstalledItemDescriptor descriptor = switch (itemType) {
case "WIDGET" -> installWidget(user, tenantId, fileData);
- case "DASHBOARD" -> installDashboard(user, tenantId, fileData);
case "CALCULATED_FIELD" -> installCalculatedField(user, tenantId, fileData, data);
case "ALARM_RULE" -> installAlarmRule(user, tenantId, fileData, data);
case "RULE_CHAIN" -> installRuleChain(user, tenantId, fileData, data);
@@ -218,22 +215,6 @@ public class DefaultIotHubService implements IotHubService {
return descriptor;
}
- private DashboardInstalledItemDescriptor installDashboard(SecurityUser user, TenantId tenantId, byte[] fileData) throws Exception {
- Dashboard dashboard;
- try {
- dashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true);
- } catch (Exception e) {
- throw parseFailure(ACTION_INSTALL, ITEM_TYPE_DASHBOARD, e);
- }
- dashboard.setId(null);
- dashboard.setTenantId(tenantId);
- Dashboard saved = tbDashboardService.save(dashboard, user);
- log.debug("[{}] Dashboard installed: {}", tenantId, saved.getTitle());
- DashboardInstalledItemDescriptor descriptor = new DashboardInstalledItemDescriptor();
- descriptor.setDashboardId(saved.getId());
- return descriptor;
- }
-
private CalculatedFieldInstalledItemDescriptor installCalculatedField(SecurityUser user, TenantId tenantId, byte[] fileData, JsonNode data) throws Exception {
CalculatedField calculatedField;
try {
@@ -435,7 +416,6 @@ public class DefaultIotHubService implements IotHubService {
switch (itemType) {
case "WIDGET" -> updateWidget(user, tenantId, (WidgetInstalledItemDescriptor) descriptor, fileData);
- case "DASHBOARD" -> updateDashboard(user, tenantId, (DashboardInstalledItemDescriptor) descriptor, fileData);
case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData);
case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData);
case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
@@ -493,22 +473,6 @@ public class DefaultIotHubService implements IotHubService {
tbWidgetTypeService.save(existing, false, user);
}
- private void updateDashboard(SecurityUser user, TenantId tenantId, DashboardInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
- Dashboard newDashboard;
- try {
- newDashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true);
- } catch (Exception e) {
- throw parseFailure(ACTION_UPDATE, ITEM_TYPE_DASHBOARD, e);
- }
- Dashboard existing = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId());
- if (existing == null) {
- throw new Exception("Dashboard not found for update");
- }
- existing.setTitle(newDashboard.getTitle());
- existing.setConfiguration(newDashboard.getConfiguration());
- tbDashboardService.save(existing, user);
- }
-
private void updateCalculatedField(SecurityUser user, TenantId tenantId, CalculatedFieldInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
CalculatedField newCf;
try {
@@ -575,8 +539,6 @@ public class DefaultIotHubService implements IotHubService {
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
if (descriptor instanceof WidgetInstalledItemDescriptor wd) {
return calculateWidgetChecksum(tenantId, wd);
- } else if (descriptor instanceof DashboardInstalledItemDescriptor dd) {
- return calculateDashboardChecksum(tenantId, dd);
} else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) {
return calculateCalculatedFieldChecksum(tenantId, cd.getCalculatedFieldId());
} else if (descriptor instanceof AlarmRuleInstalledItemDescriptor ad) {
@@ -598,16 +560,6 @@ public class DefaultIotHubService implements IotHubService {
return sha256(content);
}
- private String calculateDashboardChecksum(TenantId tenantId, DashboardInstalledItemDescriptor descriptor) {
- Dashboard dashboard = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId());
- if (dashboard == null) {
- return null;
- }
- String content = (dashboard.getTitle() != null ? dashboard.getTitle() : "") +
- (dashboard.getConfiguration() != null ? dashboard.getConfiguration().toString() : "");
- return sha256(content);
- }
-
private String calculateWidgetChecksum(TenantId tenantId, WidgetInstalledItemDescriptor descriptor) {
WidgetTypeDetails widgetType = widgetTypeService.findWidgetTypeDetailsById(tenantId, descriptor.getWidgetTypeId());
if (widgetType == null) {
@@ -780,11 +732,6 @@ public class DefaultIotHubService implements IotHubService {
if (widgetType != null) {
tbWidgetTypeService.delete(widgetType, user);
}
- } else if (descriptor instanceof DashboardInstalledItemDescriptor dd) {
- Dashboard dashboard = dashboardService.findDashboardById(tenantId, dd.getDashboardId());
- if (dashboard != null) {
- tbDashboardService.delete(dashboard, user);
- }
} else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) {
CalculatedField calculatedField = calculatedFieldService.findById(tenantId, cd.getCalculatedFieldId());
if (calculatedField != null) {
@@ -993,12 +940,13 @@ public class DefaultIotHubService implements IotHubService {
} catch (Exception e) {
log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId,
entry.getName(), entry.getVersionId(), e.getMessage(), e);
- resultEntry.setErrorMessage(e.getMessage());
+ String failureMessage = ExceptionUtil.getMessage(e);
+ resultEntry.setErrorMessage(failureMessage);
resultEntries.add(resultEntry);
boolean rolledBack = rollbackInstalledItems(user, rollbackIds);
result.setSuccess(false);
result.setRolledBack(rolledBack);
- result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage());
+ result.setErrorMessage(failureMessage);
result.setEntries(resultEntries);
result.setMissingItemIds(missingItemIds);
return result;
diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java
index 8c7deeea1b..ae777fbff7 100644
--- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java
+++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java
@@ -6,6 +6,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
+import org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier;
import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MServerSecurityConfigDefault;
import org.thingsboard.server.common.transport.config.ssl.SslCredentials;
import org.thingsboard.server.queue.util.TbCoreComponent;
@@ -14,6 +15,8 @@ import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportBootstrapConf
import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig;
import java.util.Optional;
+import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.LWM2M_SERVER_MAX;
+import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER;
@Slf4j
@Service
@@ -28,20 +31,34 @@ public class LwM2MServiceImpl implements LwM2MService {
public LwM2MServerSecurityConfigDefault getServerSecurityInfo(boolean bootstrapServer) {
LwM2MSecureServerConfig bsServerConfig = bootstrapServer ? bootstrapConfig.orElse(null) : serverConfig;
if (bsServerConfig!= null) {
- LwM2MServerSecurityConfigDefault result = getServerSecurityConfig(bsServerConfig);
- result.setBootstrapServerIs(bootstrapServer);
- return result;
+ return getServerSecurityConfig(bsServerConfig, bootstrapServer);
}
else {
return null;
}
}
- private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig) {
+ private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig, boolean bootstrapServer) {
LwM2MServerSecurityConfigDefault bsServ = new LwM2MServerSecurityConfigDefault();
- bsServ.setShortServerId(bsServerConfig.getId());
bsServ.setHost(bsServerConfig.getHost());
bsServ.setPort(bsServerConfig.getPort());
+ bsServ.setBootstrapServerIs(bootstrapServer);
+ if (bootstrapServer) {
+ if (bsServerConfig.getId() != null) {
+ log.warn("Ignoring Short Server ID [{}] on the Bootstrap Server entry: cleared to null for backward compatibility (ThingsBoard <= 4.2).",
+ bsServerConfig.getId());
+ }
+ bsServ.setShortServerId(null);
+ } else {
+ Integer configId = bsServerConfig.getId();
+ if (Lwm2mServerIdentifier.isNotLwm2mServer(configId)) {
+ log.warn("Invalid LwM2M Server ShortServerId [{}] in configuration (transport.lwm2m.server.id). " +
+ "Must be in range [{} - {}]. Using [{}] instead.",
+ configId, PRIMARY_LWM2M_SERVER.getId(), LWM2M_SERVER_MAX.getId(), PRIMARY_LWM2M_SERVER.getId());
+ configId = PRIMARY_LWM2M_SERVER.getId();
+ }
+ bsServ.setShortServerId(configId);
+ }
bsServ.setSecurityHost(bsServerConfig.getSecureHost());
bsServ.setSecurityPort(bsServerConfig.getSecurePort());
byte[] publicKeyBase64 = getPublicKey(bsServerConfig);
diff --git a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
index 39688d8c1e..18930326a9 100644
--- a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
+++ b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
@@ -7,9 +7,11 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
+import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.common.util.SetCache;
import org.thingsboard.server.cache.TbTransactionalCache;
import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.data.ApiUsageState;
@@ -85,6 +87,7 @@ import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.common.TbRuleEngineProducerService;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TopicService;
+import org.thingsboard.server.queue.discovery.event.ServiceListChangedEvent;
import org.thingsboard.server.queue.provider.TbQueueProducerProvider;
import org.thingsboard.server.service.gateway_device.GatewayNotificationsService;
import org.thingsboard.server.service.ota.OtaPackageStateService;
@@ -118,6 +121,12 @@ public class DefaultTbClusterService implements TbClusterService {
private final AtomicInteger toTransportNfs = new AtomicInteger(0);
private final AtomicInteger toEdgeMsgs = new AtomicInteger(0);
private final AtomicInteger toEdgeNfs = new AtomicInteger(0);
+ private final AtomicInteger skippedUnknownServiceNfs = new AtomicInteger(0);
+
+ private static final int RECENTLY_SEEN_SERVICES_MAX_SIZE = 1024;
+ // serviceType:serviceId -> seen. Bounded LRU of cluster members ever observed, used to grace a service id that is
+ // briefly missing from the live snapshot (see isUnknownService). Fed from ServiceListChangedEvent.
+ private final SetCache recentlySeenServices = SetCache.boundedBySize(RECENTLY_SEEN_SERVICES_MAX_SIZE);
@Autowired
private PartitionService partitionService;
@@ -197,6 +206,10 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToCore(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) {
+ if (isUnknownService(ServiceType.TB_CORE, serviceId)) {
+ skipNotificationToUnknownService(ServiceType.TB_CORE, serviceId, callback);
+ return;
+ }
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, serviceId);
log.trace("PUSHING msg: {} to:{}", response, tpi);
FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder()
@@ -211,12 +224,93 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToCore(String targetServiceId, TransportProtos.RestApiCallResponseMsgProto responseMsgProto, TbQueueCallback callback) {
+ if (isUnknownService(ServiceType.TB_CORE, targetServiceId)) {
+ skipNotificationToUnknownService(ServiceType.TB_CORE, targetServiceId, callback);
+ return;
+ }
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, targetServiceId);
ToCoreNotificationMsg msg = ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build();
producerProvider.getTbCoreNotificationsMsgProducer().send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), msg), callback);
toCoreNfs.incrementAndGet();
}
+ /**
+ * Per-service notification topics ({@code .}) are auto-created by the producer on
+ * first send. A {@code serviceId} that is not a member of the cluster - e.g. a stale node id or a value injected
+ * via message metadata - would therefore create an orphan topic that nobody ever consumes and that is never
+ * cleaned up. To prevent that, notifications whose target service id is not a current member of the cluster are
+ * skipped.
+ *
+ * This is a safety net for never-real ids, not a precise gatekeeper, so it is deliberately lenient. A service id is
+ * treated as known if it is either a current member ({@link PartitionService#isKnownServiceId}) or a recently seen
+ * one ({@link #recentlySeenServices}). The recently-seen grace covers nodes that are briefly absent from the live
+ * snapshot - a discovery-propagation lag, a rolling restart or a transient scale-down - so legitimate replies to
+ * them are not dropped; genuine non-delivery to a node that is actually gone is already handled by the caller-side
+ * RPC/REST timeout. The check also fails open while the cluster topology is not yet known (empty/absent membership,
+ * e.g. right after startup).
+ */
+ private boolean isUnknownService(ServiceType serviceType, String serviceId) {
+ if (serviceId == null || serviceId.isEmpty()) {
+ return true;
+ }
+ if (partitionService.isKnownServiceId(serviceType, serviceId)) {
+ return false; // currently a live member
+ }
+ Set serviceIds = partitionService.getAllServiceIds(serviceType);
+ if (serviceIds == null || serviceIds.isEmpty()) {
+ return false; // topology not known yet - fail open
+ }
+ return !recentlySeenServices.contains(recentlySeenServiceKey(serviceType, serviceId));
+ }
+
+ private void skipNotificationToUnknownService(ServiceType serviceType, String serviceId, TbQueueCallback callback) {
+ log.debug("Skipping notification push to unknown {} service id [{}]", serviceType, serviceId);
+ skippedUnknownServiceNfs.incrementAndGet();
+ if (callback != null) {
+ // Deliberate skip - the target is not a cluster member. Complete the callback as a no-op success,
+ // matching pushNotificationToTransport, so callers don't treat an intentional skip as a delivery error.
+ callback.onSuccess(null);
+ }
+ }
+
+ /**
+ * Records every observed cluster member so that {@link #isUnknownService} can grace a service id that has dropped
+ * out of the live snapshot (propagation lag, rolling restart, transient scale-down) instead of dropping
+ * notifications to it. Bounded by {@link #RECENTLY_SEEN_SERVICES_MAX_SIZE} with LRU eviction, so an id that is gone
+ * for good eventually ages out and the guard tightens again. Discovery events are change-only, so this never
+ * removes entries - it only adds; the live-snapshot check in {@link #isUnknownService} stays authoritative for
+ * current members.
+ */
+ @EventListener
+ public void onServiceListChanged(ServiceListChangedEvent event) {
+ rememberSeenService(event.getCurrentService());
+ List otherServices = event.getOtherServices();
+ if (otherServices != null) {
+ otherServices.forEach(this::rememberSeenService);
+ }
+ }
+
+ private void rememberSeenService(TransportProtos.ServiceInfo serviceInfo) {
+ if (serviceInfo == null) {
+ return;
+ }
+ String serviceId = serviceInfo.getServiceId();
+ if (serviceId == null || serviceId.isEmpty()) {
+ return;
+ }
+ for (String serviceType : serviceInfo.getServiceTypesList()) {
+ recentlySeenServices.add(recentlySeenServiceKey(serviceType, serviceId));
+ }
+ }
+
+ private static String recentlySeenServiceKey(ServiceType serviceType, String serviceId) {
+ return recentlySeenServiceKey(serviceType.name(), serviceId);
+ }
+
+ private static String recentlySeenServiceKey(String serviceType, String serviceId) {
+ return serviceType + ":" + serviceId;
+ }
+
@Override
public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) {
log.trace("PUSHING msg: {} to:{}", msg, tpi);
@@ -311,6 +405,10 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToRuleEngine(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) {
+ if (isUnknownService(ServiceType.TB_RULE_ENGINE, serviceId)) {
+ skipNotificationToUnknownService(ServiceType.TB_RULE_ENGINE, serviceId, callback);
+ return;
+ }
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_RULE_ENGINE, serviceId);
log.trace("PUSHING msg: {} to:{}", response, tpi);
FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder()
@@ -325,11 +423,8 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToTransport(String serviceId, ToTransportMsg response, TbQueueCallback callback) {
- if (serviceId == null || serviceId.isEmpty()) {
- log.trace("pushNotificationToTransport: skipping message without serviceId [{}], (ToTransportMsg) response [{}]", serviceId, response);
- if (callback != null) {
- callback.onSuccess(null); //callback that message already sent, no useful payload expected
- }
+ if (isUnknownService(ServiceType.TB_TRANSPORT, serviceId)) {
+ skipNotificationToUnknownService(ServiceType.TB_TRANSPORT, serviceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_TRANSPORT, serviceId);
@@ -632,9 +727,11 @@ public class DefaultTbClusterService implements TbClusterService {
int toTransportNfsCnt = toTransportNfs.getAndSet(0);
int toEdgeMsgCnt = toEdgeMsgs.getAndSet(0);
int toEdgeNfsCnt = toEdgeNfs.getAndSet(0);
- if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0) {
+ int skippedUnknownServiceNfsCnt = skippedUnknownServiceNfs.getAndSet(0);
+ if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0 || skippedUnknownServiceNfsCnt > 0) {
log.info("To TbCore: [{}] messages [{}] notifications; To TbRuleEngine: [{}] messages [{}] notifications; To Transport: [{}] notifications;" +
- "To Edge: [{}] messages [{}] notifications", toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt);
+ "To Edge: [{}] messages [{}] notifications; Skipped notifications to unknown service id: [{}]",
+ toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt, skippedUnknownServiceNfsCnt);
}
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
index 5e1ea8e44e..b0a6a490ee 100644
--- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
+++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
@@ -3,12 +3,18 @@
package org.thingsboard.server.service.rpc;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.cluster.TbClusterService;
+import org.thingsboard.server.common.data.EdgeUtils;
+import org.thingsboard.server.common.data.edge.EdgeEvent;
+import org.thingsboard.server.common.data.edge.EdgeEventActionType;
+import org.thingsboard.server.common.data.edge.EdgeEventType;
import org.thingsboard.server.common.data.id.DeviceId;
+import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.RpcId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.msg.TbMsgType;
@@ -18,9 +24,14 @@ import org.thingsboard.server.common.data.rpc.Rpc;
import org.thingsboard.server.common.data.rpc.RpcStatus;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
+import org.thingsboard.server.dao.edge.EdgeEventService;
+import org.thingsboard.server.dao.edge.EdgeService;
+import org.thingsboard.server.dao.edge.EdgeSynchronizationManager;
import org.thingsboard.server.dao.rpc.RpcService;
import org.thingsboard.server.queue.util.TbCoreComponent;
+import java.util.List;
+
@TbCoreComponent
@Service
@RequiredArgsConstructor
@@ -28,6 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
public class TbRpcService {
private final RpcService rpcService;
private final TbClusterService tbClusterService;
+ private final EdgeService edgeService;
+ private final EdgeEventService edgeEventService;
+ private final EdgeSynchronizationManager edgeSynchronizationManager;
public Rpc save(TenantId tenantId, Rpc rpc) {
Rpc saved = rpcService.save(rpc);
@@ -67,4 +81,32 @@ public class TbRpcService {
return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
}
+ /**
+ * The only edge-aware RPC delete: propagates the delete to related edges (Cloud -> Edge) for ANY status.
+ * Other delete paths (RpcService.deleteRpc, TTL clean-up) intentionally do not sync, so each side expires its own copies.
+ */
+ public void deleteRpc(TenantId tenantId, Rpc rpc) {
+ rpcService.deleteRpc(tenantId, rpc.getId());
+ // skipped when the delete originated from an edge (edge-sync context) so it is not echoed back
+ if (edgeSynchronizationManager.getEdgeId().get() == null) {
+ pushRpcDeleteToEdges(tenantId, rpc);
+ }
+ }
+
+ private void pushRpcDeleteToEdges(TenantId tenantId, Rpc rpc) {
+ List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(tenantId, rpc.getDeviceId());
+ if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) {
+ return;
+ }
+ ObjectNode body = JacksonUtil.newObjectNode();
+ body.put("requestUUID", rpc.getId().getId().toString());
+ body.put("rpcStatus", RpcStatus.DELETED.name());
+ for (EdgeId edgeId : relatedEdgeIds) {
+ // persisted (not high-priority) so the delete is replayed when the edge reconnects
+ EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, EdgeEventType.DEVICE,
+ EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body);
+ edgeEventService.saveAsync(edgeEvent);
+ }
+ }
+
}
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 84e7d928d0..f990d96af7 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
@@ -263,6 +263,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));
}
@@ -281,6 +282,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));
}
@@ -293,6 +295,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) {
@@ -302,6 +305,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));
}
@@ -320,6 +324,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/security/auth/oauth2/CookieUtils.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
index 4691f4d114..fe02ae5efb 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
@@ -2,30 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.security.jackson2.SecurityJackson2Modules;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Base64;
import java.util.Optional;
-@Slf4j
public class CookieUtils {
- private static final ObjectMapper OBJECT_MAPPER;
-
- static {
- ClassLoader loader = CookieUtils.class.getClassLoader();
- OBJECT_MAPPER = new ObjectMapper();
- OBJECT_MAPPER.registerModules(SecurityJackson2Modules.getModules(loader));
- }
-
public static Optional getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
@@ -61,24 +45,4 @@ public class CookieUtils {
}
}
}
-
- public static String serialize(Object object) {
- try {
- return Base64.getUrlEncoder()
- .encodeToString(OBJECT_MAPPER.writeValueAsBytes(object));
- } catch (JsonProcessingException e) {
- throw new IllegalArgumentException("The given Json object value: "
- + object + " cannot be transformed to a String", e);
- }
- }
-
- public static T deserialize(Cookie cookie, Class cls) {
- byte[] decodedBytes = Base64.getUrlDecoder().decode(cookie.getValue());
- try {
- return OBJECT_MAPPER.readValue(decodedBytes, cls);
- } catch (IOException e) {
- throw new IllegalArgumentException("The given string value: "
- + Arrays.toString(decodedBytes) + " cannot be transformed to Json object", e);
- }
- }
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
index 5bcda9476a..d867dc9645 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
@@ -2,13 +2,34 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
+import lombok.extern.slf4j.Slf4j;
+import org.bouncycastle.crypto.digests.SHA256Digest;
+import org.bouncycastle.crypto.generators.HKDFBytesGenerator;
+import org.bouncycastle.crypto.params.HKDFParameters;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.stereotype.Component;
import org.thingsboard.server.queue.util.TbCoreComponent;
+import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService;
+import javax.crypto.Cipher;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+import java.time.Clock;
+import java.util.Arrays;
+import java.util.Base64;
+
+@Slf4j
@Component
@TbCoreComponent
public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository {
@@ -17,10 +38,31 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
public static final String PREV_URI_COOKIE_NAME = "prev_uri";
private static final int cookieExpireSeconds = 180;
+ private static final byte[] KEY_DERIVATION_INFO = "thingsboard-oauth2-authorization-request-cookie".getBytes(StandardCharsets.UTF_8);
+ private static final int KEY_LENGTH = 32;
+ private static final int NONCE_LENGTH = 12;
+ private static final int TAG_LENGTH_BITS = 128;
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
+ .registerModules(SecurityJackson2Modules.getModules(HttpCookieOAuth2AuthorizationRequestRepository.class.getClassLoader()));
+
+ private final JwtSettingsService jwtSettingsService;
+ private final Clock clock;
+ private final SecureRandom secureRandom = new SecureRandom();
+
+ @Autowired
+ public HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService) {
+ this(jwtSettingsService, Clock.systemUTC());
+ }
+
+ HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService, Clock clock) {
+ this.jwtSettingsService = jwtSettingsService;
+ this.clock = clock;
+ }
+
@Override
public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) {
return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME)
- .map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class))
+ .map(this::decrypt)
.orElse(null);
}
@@ -34,7 +76,7 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
if (PrevUriValidator.isValid(prevUri)) {
CookieUtils.addCookie(response, PREV_URI_COOKIE_NAME, prevUri, cookieExpireSeconds);
}
- CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds);
+ CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, encrypt(authorizationRequest), cookieExpireSeconds);
}
@Override
@@ -45,4 +87,56 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) {
CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME);
}
+
+ private String encrypt(OAuth2AuthorizationRequest authorizationRequest) {
+ try {
+ byte[] json = OBJECT_MAPPER.writeValueAsBytes(authorizationRequest);
+ byte[] plaintext = ByteBuffer.allocate(Long.BYTES + json.length).putLong(clock.millis()).put(json).array();
+ byte[] nonce = new byte[NONCE_LENGTH];
+ secureRandom.nextBytes(nonce);
+ byte[] ciphertext = initCipher(Cipher.ENCRYPT_MODE, nonce).doFinal(plaintext);
+ byte[] envelope = ByteBuffer.allocate(NONCE_LENGTH + ciphertext.length).put(nonce).put(ciphertext).array();
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(envelope);
+ } catch (Exception e) {
+ throw new IllegalStateException("Failed to encrypt OAuth2 authorization request", e);
+ }
+ }
+
+ private OAuth2AuthorizationRequest decrypt(Cookie cookie) {
+ try {
+ byte[] envelope = Base64.getUrlDecoder().decode(cookie.getValue());
+ if (envelope.length < NONCE_LENGTH + TAG_LENGTH_BITS / Byte.SIZE + Long.BYTES) {
+ log.debug("Ignoring OAuth2 authorization request cookie: too short");
+ return null;
+ }
+ byte[] nonce = Arrays.copyOf(envelope, NONCE_LENGTH);
+ byte[] plaintext = initCipher(Cipher.DECRYPT_MODE, nonce).doFinal(envelope, NONCE_LENGTH, envelope.length - NONCE_LENGTH);
+ ByteBuffer buffer = ByteBuffer.wrap(plaintext);
+ long issuedAt = buffer.getLong();
+ if (clock.millis() - issuedAt > cookieExpireSeconds * 1000L) {
+ log.debug("Ignoring OAuth2 authorization request cookie: expired");
+ return null;
+ }
+ return OBJECT_MAPPER.readValue(plaintext, Long.BYTES, plaintext.length - Long.BYTES, OAuth2AuthorizationRequest.class);
+ } catch (Exception e) {
+ log.debug("Ignoring invalid OAuth2 authorization request cookie: {}", e.getClass().getSimpleName());
+ return null;
+ }
+ }
+
+ private Cipher initCipher(int mode, byte[] nonce) throws GeneralSecurityException {
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(mode, new SecretKeySpec(deriveKey(), "AES"), new GCMParameterSpec(TAG_LENGTH_BITS, nonce));
+ return cipher;
+ }
+
+ private byte[] deriveKey() {
+ byte[] signingKey = Base64.getDecoder().decode(jwtSettingsService.getJwtSettings().getTokenSigningKey());
+ HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest());
+ hkdf.init(new HKDFParameters(signingKey, null, KEY_DERIVATION_INFO));
+ byte[] key = new byte[KEY_LENGTH];
+ hkdf.generateBytes(key, 0, KEY_LENGTH);
+ return key;
+ }
+
}
diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
index 1a279b109c..e587661fc8 100644
--- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
+++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
@@ -19,7 +19,6 @@ import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Customer;
-import org.thingsboard.server.common.data.DashboardInfo;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.alarm.AlarmInfo;
@@ -30,7 +29,6 @@ import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor;
import org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery;
import org.thingsboard.server.common.data.kv.DeleteTsKvQuery;
-import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.TimePageLink;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.StringUtils;
@@ -102,6 +100,7 @@ import org.thingsboard.server.service.solutions.data.DashboardLinkInfo;
import org.thingsboard.server.service.solutions.data.DeviceCredentialsInfo;
import org.thingsboard.server.service.solutions.data.EdgeLinkInfo;
import org.thingsboard.server.service.solutions.data.SolutionInstallContext;
+import org.thingsboard.server.service.solutions.data.SolutionValidationResult;
import org.thingsboard.server.service.solutions.data.UserCredentialsInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.thingsboard.server.service.solutions.data.definition.AssetDefinition;
@@ -115,6 +114,7 @@ import org.thingsboard.server.service.solutions.data.definition.UserDefinition;
import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition;
import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition;
import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition;
+import org.thingsboard.server.service.solutions.data.definition.EntityDefinition;
import org.thingsboard.server.service.solutions.data.definition.RelationDefinition;
import org.thingsboard.server.service.solutions.data.definition.ReferenceableEntityDefinition;
import org.thingsboard.server.service.solutions.data.definition.TenantDefinition;
@@ -144,8 +144,10 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
@@ -166,6 +168,14 @@ import java.util.zip.ZipInputStream;
@Slf4j
public class DefaultSolutionService implements SolutionService {
+ private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator();
+ private static final String CONFLICTS_INTRO =
+ "Some entities of the solution template already exist. Rename or delete them and install the template again:";
+ private static final String RANDOM_PLACEHOLDER = "$random";
+ private static final int MAX_LISTED_NAMES_PER_TYPE = 10;
+ private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE
+ + " names of each type are listed. The rest are reported the next time the template is installed.";
+
@Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}")
private String docsBaseUrl;
@@ -237,9 +247,9 @@ public class DefaultSolutionService implements SolutionService {
throw new IllegalArgumentException("Solution template is missing solution.json or its 'title' field");
}
- SolutionInstallResponse validateResult = validateSolution(tenantId, tempDir);
- if (validateResult != null && !validateResult.isSuccess()) {
- return validateResult;
+ SolutionValidationResult validation = validateSolution(tenantId, tempDir);
+ if (!validation.isPassed()) {
+ return conflictResponse(validation.getConflictReport());
}
return doInstallSolution(user, tenantId, solutionId, tempDir, request);
} finally {
@@ -280,73 +290,159 @@ public class DefaultSolutionService implements SolutionService {
}
}
- private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) {
- Map> alreadyExistingEntities = new HashMap<>();
-
- //TODO: check other entities.
+ SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) {
+ //TODO: pre-validate what still only fails at provision time: customer users (unique by email),
+ // alarm rules and calculated fields.
List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() {
});
- if (!ruleChains.isEmpty()) {
- for (ReferenceableEntityDefinition ruleChain : ruleChains) {
- List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData();
- if (savedRuleChains != null && !savedRuleChains.isEmpty()) {
- alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0));
- }
- }
- }
-
List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() {
});
deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class));
- // Validate that entities with such name does not exist entities
- if (!deviceProfiles.isEmpty()) {
- for (DeviceProfile deviceProfile : deviceProfiles) {
- DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName());
- if (savedProfile != null) {
- alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile);
- }
- }
- }
-
List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() {
});
assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class));
- // Validate that entities with such name does not exist entities
- if (!assetProfiles.isEmpty()) {
- for (AssetProfile assetProfile : assetProfiles) {
- AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName());
- if (savedProfile != null) {
- alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile);
- }
+ List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() {
+ });
+ List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
+ });
+ List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() {
+ });
+ List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() {
+ });
+ List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() {
+ });
+
+ // Insertion ordered, so that the reported sections keep the order the entities are provisioned in.
+ Map> conflicts = new LinkedHashMap<>();
+ collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains);
+ collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName,
+ name -> deviceProfileService.findDeviceProfileByName(tenantId, name));
+ collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName,
+ name -> assetProfileService.findAssetProfileByName(tenantId, name));
+ collectConflicts(conflicts, customers,
+ title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null));
+ collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name));
+ collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name));
+ collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title));
+ collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name));
+
+ if (conflicts.isEmpty()) {
+ return SolutionValidationResult.passed();
+ }
+ StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE);
+ conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions));
+ if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) {
+ details.append(System.lineSeparator()).append(TRUNCATION_NOTE);
+ }
+
+ return SolutionValidationResult.conflictsFound(details.toString());
+ }
+
+ private static SolutionInstallResponse conflictResponse(String conflictReport) {
+ SolutionInstallResponse response = new SolutionInstallResponse();
+ response.setSuccess(false);
+ response.setDetails(conflictReport);
+ return response;
+ }
+
+ /**
+ * The entity type and the name both come from the definition, so a list can not end up checked against the
+ * wrong type by mistake.
+ */
+ private void collectConflicts(Map> conflicts, List extends EntityDefinition> definitions,
+ Function lookup) {
+ Set checked = new HashSet<>();
+ for (EntityDefinition definition : definitions) {
+ if (checked.add(definition.getName())) {
+ collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup);
}
}
+ }
- List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
- });
- if (!dashboards.isEmpty()) {
- for (DashboardDefinition dashboard : dashboards) {
- List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData();
- if (savedDashboards != null && !savedDashboards.isEmpty()) {
- alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0));
- }
+ private void collectConflicts(Map> conflicts, EntityType entityType, List definitions,
+ Function nameExtractor, Function lookup) {
+ Set checked = new HashSet<>();
+ for (T definition : definitions) {
+ String name = nameExtractor.apply(definition);
+ if (checked.add(name)) {
+ collectConflict(conflicts, entityType, name, lookup);
}
}
- if (!alreadyExistingEntities.isEmpty()) {
- SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse();
- StringBuilder detailsBuilder = new StringBuilder();
- detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator());
- alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ")
- .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";")
- .append(System.lineSeparator()).append(System.lineSeparator()));
- solutionInstallResponse.setSuccess(false);
- solutionInstallResponse.setDetails(detailsBuilder.toString());
- return solutionInstallResponse;
- } else {
- return null;
+ }
+
+ private void collectConflict(Map> conflicts, EntityType entityType, String name,
+ Function lookup) {
+ if (StringUtils.isEmpty(name)) {
+ return;
+ }
+ HasName existing = lookup.apply(name);
+ if (existing != null) {
+ conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName()));
+ }
+ }
+
+ /**
+ * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will
+ * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE.
+ */
+ private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir,
+ List definitions) {
+ Set checked = new HashSet<>();
+ for (ReferenceableEntityDefinition definition : definitions) {
+ if (StringUtils.isEmpty(definition.getFile())) {
+ continue;
+ }
+ Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile());
+ if (!Files.exists(ruleChainPath)) {
+ // provisionRuleChains logs and skips such a definition, so there is nothing to validate
+ continue;
+ }
+ JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain");
+ if (ruleChain == null || !ruleChain.hasNonNull("name")) {
+ continue;
+ }
+ RuleChainType type = ruleChain.hasNonNull("type")
+ ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE;
+ String name = ruleChain.get("name").asText();
+ if (!checked.add(type + name)) {
+ continue;
+ }
+ collectConflict(conflicts, EntityType.RULE_CHAIN, name,
+ ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name)
+ .stream().findFirst().orElse(null));
}
}
+ /**
+ * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random}
+ * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of
+ * every other entity are used as written, placeholder included, and must be looked up as is.
+ */
+ private static boolean isRandomizedCustomerTitle(String title) {
+ return title.contains(RANDOM_PLACEHOLDER);
+ }
+
+ private static String quoted(String value) {
+ return "'" + value + "'";
+ }
+
+ /**
+ * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads,
+ * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE}
+ * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of
+ * that type is not complete.
+ */
+ private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) {
+ details.append("- **").append(entityType.getNormalName()).append("**: ")
+ .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", ")));
+ if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) {
+ details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE)
+ .append(" more (").append(conflictDescriptions.size()).append(" in total)");
+ }
+ details.append(System.lineSeparator());
+ }
+
private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) {
SolutionInstallContext ctx = new SolutionInstallContext(tenantId, solutionId, tempDir, user, new TenantSolutionTemplateInstructions());
@@ -1442,10 +1538,6 @@ public class DefaultSolutionService implements SolutionService {
return String.valueOf(now.toInstant().toEpochMilli());
}
- private String getTypeLabel(EntityType type) {
- return type.name().toLowerCase().replace('_', ' ');
- }
-
private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) {
Path filePath = tempDir.resolve("entities").resolve(fileName);
if (Files.exists(filePath)) {
@@ -1459,7 +1551,7 @@ public class DefaultSolutionService implements SolutionService {
Path filePath = tempDir.resolve("entities").resolve(fileName);
if (Files.exists(filePath)) {
try {
- return JacksonUtil.readValue(filePath.toFile(), typeReference);
+ return Objects.requireNonNullElseGet(JacksonUtil.readValue(filePath.toFile(), typeReference), ArrayList::new);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java
new file mode 100644
index 0000000000..4b6b07c54b
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java
@@ -0,0 +1,30 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.solutions.data;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+/**
+ * The outcome of validating a solution template before anything is created: either the install can go ahead, or the
+ * entities of the tenant the template clashes with, reported as the markdown the install dialog renders.
+ */
+@Getter
+@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
+public class SolutionValidationResult {
+
+ private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, "");
+
+ private final boolean passed;
+ private final String conflictReport;
+
+ public static SolutionValidationResult passed() {
+ return PASSED;
+ }
+
+ public static SolutionValidationResult conflictsFound(String conflictReport) {
+ return new SolutionValidationResult(false, conflictReport);
+ }
+
+}
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 d97d2c5ddf..c1391f111b 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
@@ -93,19 +93,7 @@ public class SystemPatchApplier {
try {
String dbVersion = schemaSettingsService.getDbSchemaVersion();
String packageVersion = schemaSettingsService.getPackageSchemaVersion();
- ltsMigrationService.applyMigrations(dbVersion, packageVersion);
-
- updateSqlViews();
- log.info("Updated sql database views");
-
- WidgetTypeStats widgetStats = updateWidgetTypes();
- log.info("System widget types: {} created, {} updated", widgetStats.created(), widgetStats.updated());
-
- int updatedBundles = updateWidgetBundles();
- log.info("System widget bundles: {} updated", updatedBundles);
-
- int createdImages = createMissingSystemImages();
- log.info("Created {} new system images", createdImages);
+ ltsMigrationService.applyMigrations(dbVersion, packageVersion, this::syncSystemData);
schemaSettingsService.updateSchemaVersion();
log.info("System data patch update completed successfully");
@@ -115,6 +103,21 @@ public class SystemPatchApplier {
}
}
+ // Views are rebuilt with SELECT * over tables the migrations may have altered, so this must run after them.
+ private void syncSystemData() {
+ updateSqlViews();
+ log.info("Updated sql database views");
+
+ WidgetTypeStats widgetStats = updateWidgetTypes();
+ log.info("System widget types: {} created, {} updated", widgetStats.created(), widgetStats.updated());
+
+ int updatedBundles = updateWidgetBundles();
+ log.info("System widget bundles: {} updated", updatedBundles);
+
+ int createdImages = createMissingSystemImages();
+ log.info("Created {} new system images", createdImages);
+ }
+
private boolean isVersionChanged() {
String packageVersion = schemaSettingsService.getPackageSchemaVersion();
String dbVersion = schemaSettingsService.getDbSchemaVersion();
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 54c5d271e1..da1a748c37 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
@@ -19,7 +19,9 @@ import org.thingsboard.server.common.data.kv.ReadTsKvQuery;
import org.thingsboard.server.common.data.kv.TsKvEntry;
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 org.thingsboard.server.service.security.permission.Operation;
@@ -42,6 +44,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)) {
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 71f4e73929..15e470085b 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
@@ -882,72 +882,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/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml
index 5bf7eda87b..d0fa7565f9 100644
--- a/application/src/main/resources/thingsboard.yml
+++ b/application/src/main/resources/thingsboard.yml
@@ -43,7 +43,8 @@ server:
# HTTP settings
http:
# Semi-colon-separated list of urlPattern=maxPayloadSize pairs that define max http request size for specified url pattern. After first match all other will be skipped
- max_payload_size: "${HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}"
+ # The /api/communityGrant/offline/run entry must precede /api/** to allow instance checker uploads; it is prepended automatically if missing
+ max_payload_size: "${HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:/api/communityGrant/offline/run=35651584;/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}"
# HTTP/2 support (takes effect only if server SSL is enabled)
http2:
# Enable/disable HTTP/2 support
@@ -1291,7 +1292,7 @@ transport:
#
A value that are > 4: MultiNodeConnectionIdGenerator is used