Browse Source

Merge remote-tracking branch 'upstream/lts-4.2' into fix/edge-activity-state-guard-followups-lts-4.2

# Conflicts:
#	application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
pull/16162/head
Nikita Mazurenko 1 month ago
parent
commit
158f4f5148
  1. 4
      TEST_FAST.md
  2. 2
      application/pom.xml
  3. 9
      application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
  4. 17
      application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java
  5. 4
      application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
  6. 12
      application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
  7. 271
      application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
  8. 49
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
  9. 60
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  10. 111
      application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
  11. 42
      application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
  12. 5
      application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
  13. 36
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
  14. 98
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
  15. 212
      application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
  16. 30
      application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java
  17. 6
      application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java
  18. 76
      application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java
  19. 2
      application/src/main/resources/thingsboard.yml
  20. 6
      application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
  21. 7
      application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java
  22. 3
      application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java
  23. 36
      application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java
  24. 48
      application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java
  25. 12
      application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java
  26. 119
      application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
  27. 9
      application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java
  28. 325
      application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java
  29. 191
      application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java
  30. 70
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  31. 7
      application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java
  32. 205
      application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java
  33. 86
      application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java
  34. 14
      application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java
  35. 45
      application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java
  36. 151
      application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java
  37. 294
      application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java
  38. 2
      common/actor/pom.xml
  39. 2
      common/cache/pom.xml
  40. 2
      common/cluster-api/pom.xml
  41. 2
      common/coap-server/pom.xml
  42. 6
      common/dao-api/pom.xml
  43. 2
      common/data/pom.xml
  44. 13
      common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java
  45. 1
      common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java
  46. 11
      common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java
  47. 10
      common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java
  48. 2
      common/discovery-api/pom.xml
  49. 2
      common/edge-api/pom.xml
  50. 2
      common/edge-api/src/main/proto/edge.proto
  51. 2
      common/edqs/pom.xml
  52. 2
      common/message/pom.xml
  53. 2
      common/pom.xml
  54. 2
      common/proto/pom.xml
  55. 7
      common/queue/pom.xml
  56. 19
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java
  57. 6
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java
  58. 100
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java
  59. 189
      common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java
  60. 109
      common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java
  61. 2
      common/script/pom.xml
  62. 2
      common/script/remote-js-client/pom.xml
  63. 2
      common/script/script-api/pom.xml
  64. 26
      common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java
  65. 109
      common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java
  66. 2
      common/stats/pom.xml
  67. 2
      common/transport/coap/pom.xml
  68. 2
      common/transport/http/pom.xml
  69. 2
      common/transport/lwm2m/pom.xml
  70. 2
      common/transport/mqtt/pom.xml
  71. 2
      common/transport/pom.xml
  72. 2
      common/transport/snmp/pom.xml
  73. 2
      common/transport/transport-api/pom.xml
  74. 2
      common/util/pom.xml
  75. 16
      common/util/src/main/java/org/thingsboard/common/util/SetCache.java
  76. 6
      common/version-control/pom.xml
  77. 6
      dao/pom.xml
  78. 2
      edqs/pom.xml
  79. 2
      monitoring/pom.xml
  80. 2
      msa/black-box-tests/pom.xml
  81. 2
      msa/edqs/pom.xml
  82. 2
      msa/js-executor/docker/Dockerfile
  83. 7
      msa/js-executor/package.json
  84. 23
      msa/js-executor/pom.xml
  85. 231
      msa/js-executor/yarn.lock
  86. 2
      msa/monitoring/pom.xml
  87. 38
      msa/pom.xml
  88. 2
      msa/tb-node/pom.xml
  89. 2
      msa/tb/pom.xml
  90. 2
      msa/transport/coap/pom.xml
  91. 2
      msa/transport/http/pom.xml
  92. 2
      msa/transport/lwm2m/pom.xml
  93. 2
      msa/transport/mqtt/pom.xml
  94. 2
      msa/transport/pom.xml
  95. 2
      msa/transport/snmp/pom.xml
  96. 2
      msa/vc-executor-docker/pom.xml
  97. 2
      msa/vc-executor/pom.xml
  98. 2
      msa/web-ui/docker/Dockerfile
  99. 9
      msa/web-ui/package.json
  100. 5
      msa/web-ui/pom.xml

4
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

2
application/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>thingsboard</artifactId>
</parent>
<artifactId>application</artifactId>

9
application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java

@ -11,6 +11,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;
@ -34,6 +35,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;
@ -61,6 +63,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. " +
@ -217,13 +222,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()

17
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<Authority> USER_AUTHORITIES = EnumSet.of(Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER);
private final ConcurrentMap<String, SessionMetaData> internalSessionMap = new ConcurrentHashMap<>();
private final ConcurrentMap<String, String> 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) {

4
application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java

@ -45,6 +45,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.alarm.AlarmProcessor;
import org.thingsboard.server.service.edge.rpc.processor.alarm.comment.AlarmCommentProcessor;
@ -121,6 +122,9 @@ public class EdgeContextComponent {
@Autowired
private DeviceService deviceService;
@Autowired
private TbRpcService tbRpcService;
@Autowired
private DomainService domainService;

12
application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java

@ -259,20 +259,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());
}
@ -299,6 +302,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;
}

271
application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java

@ -73,9 +73,12 @@ import java.util.concurrent.ConcurrentMap;
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;
@ -302,13 +305,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 {
@ -316,7 +316,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
} finally {
newEventLock.unlock();
}
cancelScheduleEdgeEventsCheck(edgeId);
destroySession(toRemove);
toRemove.cleanUp();
}
}
@ -357,16 +358,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 {
@ -382,9 +379,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
long lastConnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs);
pushRuleEngineMessage(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT);
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) {
@ -446,54 +445,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);
}
}
@ -527,53 +545,21 @@ 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;
// - on this branch the EDGE_CONNECTION (disconnected) notification is raised from inside
// pushRuleEngineMessage, so it is suppressed together with the event. That is the point: a
// connected edge must not produce a 'disconnected' notification, and this branch has no
// delayed re-verify to withdraw one after the fact.
// 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)) {
save(tenantId, edgeId, ACTIVITY_STATE, false);
// Skip all disconnect side effects if a newer session already owns the edge, on this or another node.
// The local check and the inactive write are atomic with attachSession.
if (!isOwnedByAnotherNode(edgeId) && markInactiveIfNoSession(tenantId, edgeId)) {
long lastDisconnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs);
pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
}
// 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 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);
pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
}
destroySession(toRemove);
} else {
log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId);
EdgeGrpcSession stale = sessionsById.remove(sessionId);
@ -588,9 +574,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId);
}
}
// Only evict if no live session holds this edge on this node any more and the cache still points
// here. If the edge already reconnected - to this node or to another one - that session owns the
// entry, and evicting it would wipe the live owner's claim and defeat the activity-state guard above.
// Only evict if the cache still points at this node and no live session for this edge is left here.
// If the edge already reconnected to another TB-Core node, that node has overwritten the entry and owns it;
// if a newer session on this node replaced a stale one, that session owns it - evicting in either case
// would wipe the live owner's claim and defeat the activity-state guard above.
if (!sessions.containsKey(edgeId) && isOwnedByThisNode(edgeId)) {
edgeIdServiceIdCache.evict(edgeId);
}
@ -603,11 +590,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<String> wrapper = edgeIdServiceIdCache.get(edgeId);
if (wrapper == null) {
@ -626,6 +608,71 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
return wrapper != null && serviceInfoProvider.getServiceId().equals(wrapper.get());
}
/**
* 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.
* <p>
* 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<EdgeGrpcSession> replaced = new AtomicReference<>();
sessions.compute(edgeId, (id, current) -> {
replaced.set(current);
cancelScheduleEdgeEventsCheck(edgeId);
return session;
});
return replaced.get();
}
private boolean markInactiveIfNoSession(TenantId tenantId, EdgeId edgeId) {
AtomicBoolean marked = new AtomicBoolean();
sessions.compute(edgeId, (id, current) -> {
if (current == null) {
save(tenantId, edgeId, ACTIVITY_STATE, false);
marked.set(true);
}
return current;
});
return marked.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.
* <p>
* 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<EdgeGrpcSession> shouldDetach) {
AtomicReference<EdgeGrpcSession> 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();
}
/**
* 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()) {
@ -745,10 +792,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 -> {

49
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;
@ -125,7 +129,10 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
@Override
public ListenableFuture<Void> 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);
@ -133,6 +140,46 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
return Futures.immediateFuture(null);
}
private ListenableFuture<Void> 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<Void> processDeviceRpcResponseFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) {
SettableFuture<Void> futureToSet = SettableFuture.create();
UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB());

60
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.exception.ThingsboardException;
@ -22,7 +22,6 @@ import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
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;
@ -78,7 +77,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_RULE_CHAIN = "rule chain";
private static final String ITEM_TYPE_DEVICE_PROFILE = "device profile";
@ -149,7 +147,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" -> throw new IllegalArgumentException(
"Alarm Rules require ThingsBoard 4.3 or later. Please update your platform instance to install Alarm Rule packages.");
@ -211,22 +208,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 {
@ -404,7 +385,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 "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
case "DEVICE" -> {
@ -461,22 +441,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 {
@ -523,8 +487,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);
} else if (descriptor instanceof RuleChainInstalledItemDescriptor rd) {
@ -544,16 +506,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) {
@ -726,11 +678,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) {
@ -934,12 +881,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;

111
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;
@ -83,6 +85,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;
@ -116,6 +119,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<String> recentlySeenServices = SetCache.boundedBySize(RECENTLY_SEEN_SERVICES_MAX_SIZE);
@Autowired
private PartitionService partitionService;
@ -195,6 +204,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()
@ -209,12 +222,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 <notifications-topic>.<serviceId>}) 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.
* <p>
* 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<String> 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<TransportProtos.ServiceInfo> 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);
@ -309,6 +403,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()
@ -323,11 +421,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);
@ -617,9 +712,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);
}
}
}

42
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<EdgeId> 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);
}
}
}

5
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));
}

36
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<Cookie> 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> T deserialize(Cookie cookie, Class<T> 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);
}
}
}

98
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<OAuth2AuthorizationRequest> {
@ -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;
}
}

212
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;
@ -29,7 +28,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;
@ -100,6 +98,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;
@ -113,6 +112,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;
@ -142,8 +142,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;
@ -164,6 +166,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;
@ -235,9 +245,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 {
@ -278,73 +288,159 @@ public class DefaultSolutionService implements SolutionService {
}
}
private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) {
Map<EntityType, List<HasName>> 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<ReferenceableEntityDefinition> ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() {
});
if (!ruleChains.isEmpty()) {
for (ReferenceableEntityDefinition ruleChain : ruleChains) {
List<RuleChain> 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<DeviceProfileDefinition> 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<AssetProfileDefinition> 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<CustomerDefinition> customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() {
});
List<DashboardDefinition> dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
});
List<AssetDefinition> assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() {
});
List<DeviceDefinition> devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() {
});
List<EdgeDefinition> edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() {
});
// Insertion ordered, so that the reported sections keep the order the entities are provisioned in.
Map<EntityType, List<String>> 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<EntityType, List<String>> conflicts, List<? extends EntityDefinition> definitions,
Function<String, ? extends HasName> lookup) {
Set<String> checked = new HashSet<>();
for (EntityDefinition definition : definitions) {
if (checked.add(definition.getName())) {
collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup);
}
}
}
List<DashboardDefinition> dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
});
if (!dashboards.isEmpty()) {
for (DashboardDefinition dashboard : dashboards) {
List<DashboardInfo> 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 <T> void collectConflicts(Map<EntityType, List<String>> conflicts, EntityType entityType, List<T> definitions,
Function<T, String> nameExtractor, Function<String, ? extends HasName> lookup) {
Set<String> 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<EntityType, List<String>> conflicts, EntityType entityType, String name,
Function<String, ? extends HasName> 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<EntityType, List<String>> conflicts, TenantId tenantId, Path tempDir,
List<ReferenceableEntityDefinition> definitions) {
Set<String> 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<String> 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());
@ -1437,10 +1533,6 @@ public class DefaultSolutionService implements SolutionService {
return String.valueOf(now.toInstant().toEpochMilli());
}
private String getTypeLabel(EntityType type) {
return type.name().toLowerCase().replace('_', ' ');
}
private <T> T loadEntityIfFileExists(Path tempDir, String fileName, Class<T> clazz) {
Path filePath = tempDir.resolve("entities").resolve(fileName);
if (Files.exists(filePath)) {
@ -1454,7 +1546,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);
}

30
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);
}
}

6
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)) {

76
application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java

@ -882,72 +882,36 @@ public class DefaultWebSocketService implements WebSocketService {
}, executor);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@Override
public void onSuccess(@Nullable ValidationResult result) {
List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
for (AttributeScope scope : AttributeScope.values()) {
futures.add(attributesService.find(tenantId, entityId, scope, keys));
}
ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
private FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> {
List<ListenableFuture<List<AttributeKvEntry>>> 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<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
}, callback::onFailure);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@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<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor()), callback::onFailure);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@Override
public void onSuccess(@Nullable ValidationResult result) {
List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
for (AttributeScope scope : AttributeScope.values()) {
futures.add(attributesService.findAll(tenantId, entityId, scope));
}
ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
private FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> {
List<ListenableFuture<List<AttributeKvEntry>>> 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<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
}, callback::onFailure);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@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<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()), callback::onFailure);
}
private FutureCallback<ValidationResult> on(Consumer<Void> success, Consumer<Throwable> failure) {

2
application/src/main/resources/thingsboard.yml

@ -1428,7 +1428,7 @@ transport:
# URL of gateways dashboard repository
repository_url: "${TB_GATEWAY_DASHBOARD_SYNC_REPOSITORY_URL:https://github.com/thingsboard/gateway-management-extensions-dist.git}"
# Branch of gateways dashboard repository to work with
branch: "${TB_GATEWAY_DASHBOARD_SYNC_BRANCH:release/4.0.0}"
branch: "${TB_GATEWAY_DASHBOARD_SYNC_BRANCH:release/4.2.0}"
# Fetch frequency in hours for gateways dashboard repository
fetch_frequency: "${TB_GATEWAY_DASHBOARD_SYNC_FETCH_FREQUENCY:24}"
ssl:

6
application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java

@ -92,7 +92,7 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest {
}
protected TbTestWebSocketClient buildAndConnectWebSocketClient(String path) throws URISyntaxException, InterruptedException {
TbTestWebSocketClient wsClient = new TbTestWebSocketClient(new URI(WS_URL + wsPort + path));
TbTestWebSocketClient wsClient = buildWebSocketClient(path);
assertThat(wsClient.connectBlocking(TIMEOUT, TimeUnit.SECONDS)).isTrue();
if (!path.contains("token=")) {
wsClient.authenticate(token);
@ -100,4 +100,8 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest {
return wsClient;
}
protected TbTestWebSocketClient buildWebSocketClient(String path) throws URISyntaxException {
return new TbTestWebSocketClient(new URI(WS_URL + wsPort + path));
}
}

7
application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java

@ -360,8 +360,13 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
}
private void testSendNotificationMsgToEdgeServiceTimeEntityEqAny(TenantId tenantId, ActionType actionType, int cntTime) {
// Count only entities that can be synced to edge. Background services may save non-edge entities for the
// tenant at any moment (e.g. QUEUE_STATS created by the periodic rule engine stats report), and their
// ADDED notifications have no edge event type, so they are dropped by TbClusterService anyway.
ArgumentMatcher<EntityId> matcherEdgeEntityId = argument -> argument != null
&& EdgeUtils.getEdgeEventTypeByEntityType(argument.getEntityType()) != null;
Mockito.verify(tbClusterService, times(cntTime)).sendNotificationMsgToEdge(Mockito.eq(tenantId),
Mockito.any(), Mockito.any(EntityId.class), Mockito.any(), Mockito.isNull(),
Mockito.any(), Mockito.argThat(matcherEdgeEntityId), Mockito.any(), Mockito.isNull(),
Mockito.eq(EdgeUtils.getEdgeEventActionTypeByActionType(actionType)), Mockito.any());
}

3
application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java

@ -42,6 +42,8 @@ public class TbTestWebSocketClient extends WebSocketClient {
@Getter
private volatile String lastMsg;
@Getter
private volatile Integer closeCode;
private volatile CountDownLatch reply;
private volatile CountDownLatch update;
@ -74,6 +76,7 @@ public class TbTestWebSocketClient extends WebSocketClient {
@Override
public void onClose(int i, String s, boolean b) {
closeCode = i;
log.info("CLOSED.");
}

36
application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java

@ -7,8 +7,10 @@ import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.SaveDeviceWithCredentialsRequest;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.kv.BasicTsKvEntry;
import org.thingsboard.server.common.data.kv.LongDataEntry;
import org.thingsboard.server.common.data.query.AliasEntityId;
@ -19,9 +21,11 @@ import org.thingsboard.server.common.data.security.DeviceCredentialsType;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.thingsboard.server.common.data.query.EntityKeyType.TIME_SERIES;
@ -219,6 +223,38 @@ public class TelemetryControllerTest extends AbstractControllerTest {
doPostAsync("/api/plugins/telemetry/DEVICE/" + device.getId() + "/timeseries/smth", invalidRequestBody2, String.class, status().isBadRequest());
}
@Test
public void testCustomerUserCannotReadTimeseriesOfNotAssignedDevice() throws Exception {
loginTenantAdmin();
Device device = createDevice();
tsService.save(tenantId, device.getId(), new BasicTsKvEntry(1000L, new LongDataEntry("t", 1L))).get();
loginCustomerUser();
String url = "/api/plugins/telemetry/DEVICE/{entityId}/values/timeseries?keys=t&startTs=0&endTs={endTs}";
doGetAsync(url, device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden());
doGetAsync(url + "&agg=SUM&interval=86400000", device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden());
doGetAsync(url, UUID.randomUUID(), System.currentTimeMillis()).andExpect(status().isNotFound());
loginTenantAdmin();
assignDeviceToCustomer(device.getId(), customerId);
loginCustomerUser();
ObjectNode result = doGetAsync(url, ObjectNode.class, device.getUuidId(), System.currentTimeMillis());
Assert.assertEquals(1L, result.get("t").get(0).get("value").asLong());
}
@Test
public void testCustomerUserCannotSaveDeviceProfileAttributes() throws Exception {
loginTenantAdmin();
DeviceProfileId deviceProfileId = createDevice().getDeviceProfileId();
loginCustomerUser();
doPostAsync("/api/plugins/telemetry/DEVICE_PROFILE/" + deviceProfileId + "/SERVER_SCOPE", "{\"attr\": \"value\"}", String.class, status().isForbidden());
await().during(1, TimeUnit.SECONDS).atMost(2, TimeUnit.SECONDS)
.until(() -> attributesService.find(tenantId, deviceProfileId, AttributeScope.SERVER_SCOPE, "attr").get().isEmpty());
}
private Device createDevice() throws Exception {
String testToken = "TEST_TOKEN";

48
application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java

@ -4,6 +4,7 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.java_websocket.framing.CloseFrame;
import org.jboss.aerogear.security.otp.Totp;
import org.junit.After;
import org.junit.Before;
@ -13,6 +14,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.thingsboard.rule.engine.api.SmsService;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionStatus;
@ -23,6 +26,8 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.SortOrder;
import org.thingsboard.server.common.data.page.TimePageLink;
import org.thingsboard.server.common.data.query.EntityData;
import org.thingsboard.server.common.data.query.EntityTypeFilter;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.security.model.JwtPair;
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings;
@ -40,6 +45,7 @@ import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService;
import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager;
import org.thingsboard.server.service.security.auth.rest.LoginRequest;
import org.thingsboard.server.service.ws.telemetry.cmd.v2.EntityDataUpdate;
import java.time.Duration;
import java.util.Arrays;
@ -141,6 +147,48 @@ public class TwoFactorAuthTest extends AbstractControllerTest {
assertThat(currentUser.getId()).isEqualTo(user.getId());
}
@Test
public void testWsAuthCmd_preVerificationTokenRejected() throws Exception {
configureTotpTwoFa();
logInWithPreVerificationToken(username, password);
wsClient = buildAndConnectWebSocketClient();
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed);
}
@Test
public void testWsQueryToken_preVerificationTokenRejected() throws Exception {
configureTotpTwoFa();
logInWithPreVerificationToken(username, password);
// The server accepts the handshake and closes the session right away from afterConnectionEstablished().
// connectBlocking() returns false when that close frame is processed before it checks the open state,
// so its result is not asserted here; the server-side close code proves the token was rejected.
wsClient = buildWebSocketClient("/api/ws?token=" + token);
wsClient.connectBlocking(TIMEOUT, TimeUnit.SECONDS);
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed);
assertThat(wsClient.getCloseCode()).isEqualTo(CloseFrame.UNEXPECTED_CONDITION);
}
@Test
public void testWs_accessTokenAcceptedAfterTwoFa() throws Exception {
TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa();
logInWithPreVerificationToken(username, password);
JsonNode tokenPair = readResponse(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + getCorrectTotp(totpTwoFaAccountConfig))
.andExpect(status().isOk()), JsonNode.class);
validateAndSetJwtToken(tokenPair, username);
Device device = createDevice("2FA device", "2FA device token");
EntityTypeFilter deviceFilter = new EntityTypeFilter();
deviceFilter.setEntityType(EntityType.DEVICE);
EntityDataUpdate update = getWsClient().sendEntityDataQuery(deviceFilter);
assertThat(update.getData().getData()).singleElement()
.extracting(EntityData::getEntityId).isEqualTo(device.getId());
}
@Test
public void testTwoFaPreVerificationTokenLifetime() throws Exception {
configureTotpTwoFa(twoFaSettings -> {

12
application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java

@ -966,6 +966,18 @@ public class WebsocketApiTest extends AbstractControllerTest {
assertThat(update.get("data").get("attr").get(0).get(1).asText()).isEqualTo(expectedAttrValue);
}
@Test
public void testAttributesSubscription_customerUserNotAssignedDevice() throws Exception {
sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, List.of(
new BaseAttributeKvEntry(System.currentTimeMillis(), new StringDataEntry("attr", "secret"))
));
loginCustomerUser();
JsonNode update = getWsClient().subscribeForAttributes(device.getId(), TbAttributeSubscriptionScope.SERVER_SCOPE.name(), List.of("attr"));
assertThat(update.get("errorCode").asInt()).isNotEqualTo(SubscriptionErrorCode.NO_ERROR.getCode());
assertThat(update.path("data").isEmpty()).isTrue();
}
@Test
public void testEntityCountCmd_filterTypeSingularCompatibilityTest() throws Exception {
ObjectNode oldFormatDeviceTypeFilterSingular = JacksonUtil.newObjectNode();

119
application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java

@ -38,14 +38,18 @@ import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.RpcId;
import org.thingsboard.server.common.data.ota.OtaPackageType;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.rpc.Rpc;
import org.thingsboard.server.common.data.rpc.RpcStatus;
import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.common.data.security.DeviceCredentialsType;
import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration;
import org.thingsboard.server.common.msg.session.FeatureType;
import org.thingsboard.server.dao.edge.EdgeService;
import org.thingsboard.server.dao.rpc.RpcService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.gen.edge.v1.AttributesRequestMsg;
import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg;
@ -94,6 +98,9 @@ public class DeviceEdgeTest extends AbstractEdgeTest {
@Autowired
protected EdgeService edgeService;
@Autowired
protected RpcService rpcService;
@Test
public void testDevices() throws Exception {
// create device and assign to edge; update device
@ -657,6 +664,118 @@ public class DeviceEdgeTest extends AbstractEdgeTest {
Assert.assertEquals(2, latestDeviceRpcCallMsg.getRetries());
}
@Test
public void testRpcV2StatusUpdateFromEdge() throws Exception {
Device device = findDeviceByName("Edge Device 1");
Rpc rpc = savePersistentRpc(device, RpcStatus.QUEUED);
sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null);
Assert.assertEquals(RpcStatus.DELIVERED, getPersistentRpc(rpc.getId()).getStatus());
sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "{\"result\":\"ok\"}");
Rpc successful = getPersistentRpc(rpc.getId());
Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus());
Assert.assertEquals("ok", successful.getResponse().get("result").asText());
// stale intermediate status must not regress a final RPC
sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null);
Assert.assertEquals(RpcStatus.SUCCESSFUL, getPersistentRpc(rpc.getId()).getStatus());
}
@Test
public void testRpcV2StatusRetryAfterTimeoutFromEdge() throws Exception {
Device device = findDeviceByName("Edge Device 1");
Rpc rpc = savePersistentRpc(device, RpcStatus.SENT);
// TIMEOUT with retries left is followed by a re-delivery
sendRpcStatusUplink(device, rpc.getId(), RpcStatus.TIMEOUT, null);
Assert.assertEquals(RpcStatus.TIMEOUT, getPersistentRpc(rpc.getId()).getStatus());
sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SENT, null);
Assert.assertEquals(RpcStatus.SENT, getPersistentRpc(rpc.getId()).getStatus());
}
@Test
public void testRpcV2NonJsonResponseFromEdge() throws Exception {
Device device = findDeviceByName("Edge Device 1");
Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED);
sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "not a json");
Rpc successful = getPersistentRpc(rpc.getId());
Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus());
Assert.assertEquals("not a json", successful.getResponse().get("error").asText());
}
@Test
public void testRpcV2StatusForUnknownRpcFromEdge() throws Exception {
Device device = findDeviceByName("Edge Device 1");
RpcId unknownRpcId = new RpcId(Uuids.timeBased());
sendRpcStatusUplink(device, unknownRpcId, RpcStatus.DELIVERED, null);
doGet("/api/rpc/persistent/" + unknownRpcId.getId()).andExpect(status().isNotFound());
}
@Test
public void testRpcV2DeleteFromEdge() throws Exception {
Device device = findDeviceByName("Edge Device 1");
Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED);
edgeImitator.expectMessageAmount(1);
sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELETED, null);
doGet("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isNotFound());
// delete originated from the edge must not be echoed back
Assert.assertFalse(edgeImitator.waitForMessages(1));
}
@Test
public void testRpcV2DeleteFromCloud() throws Exception {
Device device = findDeviceByName("Edge Device 1");
Rpc rpc = savePersistentRpc(device, RpcStatus.SUCCESSFUL);
edgeImitator.expectMessageAmount(1);
doDelete("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isOk());
Assert.assertTrue(edgeImitator.waitForMessages());
AbstractMessage latestMessage = edgeImitator.getLatestMessage();
Assert.assertTrue(latestMessage instanceof DeviceRpcCallMsg);
DeviceRpcCallMsg deviceRpcCallMsg = (DeviceRpcCallMsg) latestMessage;
Assert.assertEquals(RpcStatus.DELETED.name(), deviceRpcCallMsg.getRpcStatus());
Assert.assertEquals(rpc.getUuidId(), new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB()));
Assert.assertFalse(deviceRpcCallMsg.hasRequestMsg());
Assert.assertFalse(deviceRpcCallMsg.hasResponseMsg());
}
private Rpc savePersistentRpc(Device device, RpcStatus status) {
Rpc rpc = new Rpc(new RpcId(Uuids.timeBased()));
rpc.setTenantId(tenantId);
rpc.setDeviceId(device.getId());
rpc.setExpirationTime(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1));
rpc.setRequest(JacksonUtil.newObjectNode().put("method", "test_method"));
rpc.setStatus(status);
return rpcService.save(rpc);
}
private Rpc getPersistentRpc(RpcId rpcId) throws Exception {
return doGet("/api/rpc/persistent/" + rpcId.getId(), Rpc.class);
}
private void sendRpcStatusUplink(Device device, RpcId rpcId, RpcStatus rpcStatus, String response) throws Exception {
DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder()
.setDeviceIdMSB(device.getUuidId().getMostSignificantBits())
.setDeviceIdLSB(device.getUuidId().getLeastSignificantBits())
.setRequestUuidMSB(rpcId.getId().getMostSignificantBits())
.setRequestUuidLSB(rpcId.getId().getLeastSignificantBits())
.setRpcStatus(rpcStatus.name());
if (response != null) {
builder.setResponseMsg(RpcResponseMsg.newBuilder().setResponse(response).build());
}
UplinkMsg uplinkMsg = UplinkMsg.newBuilder().addDeviceRpcCallMsg(builder.build()).build();
edgeImitator.expectResponsesAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsg);
Assert.assertTrue(edgeImitator.waitForResponses());
}
private void sendAttributesRequestAndVerify(Device device, String scope, String attributesDataStr, String expectedKey,
String expectedValue) throws Exception {
JsonNode attributesData = JacksonUtil.toJsonNode(attributesDataStr);

9
application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java

@ -83,6 +83,7 @@ public class HashPartitionServiceTest {
.setServiceId("tb-core-0")
.addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name()))
.build();
when(serviceInfoProvider.getServiceInfo()).thenReturn(currentServer);
List<ServiceInfo> otherServers = new ArrayList<>();
for (int i = 1; i < SERVER_COUNT; i++) {
otherServers.add(ServiceInfo.newBuilder()
@ -94,6 +95,14 @@ public class HashPartitionServiceTest {
partitionService.recalculatePartitions(currentServer, otherServers);
}
@Test
public void testIsKnownServiceId() {
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-core-0")).isTrue(); // current server
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-rule-1")).isTrue(); // other server
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "unknown-id")).isFalse();
assertThat(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, "tb-core-0")).isFalse(); // wrong type
}
@Test
public void testDispersionOnMillionDevices() {
List<DeviceId> devices = new ArrayList<>();

325
application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java

@ -0,0 +1,325 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.edge.rpc;
import com.google.common.util.concurrent.Futures;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.cache.SimpleTbCacheValueWrapper;
import org.thingsboard.server.cache.TbTransactionalCache;
import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor;
import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg;
import org.thingsboard.server.queue.TbQueueConsumer;
import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.common.consumer.QueueConsumerManager;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import org.thingsboard.server.service.edge.EdgeContextComponent;
import org.thingsboard.server.service.executors.GrpcCallbackExecutorService;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Covers the reconnect race between a session that is being torn down and the session that has already
* taken the edge over: the teardown must not detach, cancel the edge event check of, or consume the new
* events flag of the session that replaced it.
*/
class EdgeGrpcServiceReconnectTest {
// long enough that an armed check never actually fires during a test
private static final long NO_RECORDS_SLEEP_INTERVAL_MS = 60_000L;
private static final String THIS_NODE = "test-core";
private EdgeGrpcService service;
private ScheduledExecutorService edgeEventProcessingExecutorService;
private TbTransactionalCache<EdgeId, String> edgeIdServiceIdCache;
private TenantId tenantId;
private EdgeId edgeId;
private Edge edge;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
tenantId = TenantId.fromUUID(UUID.randomUUID());
edgeId = new EdgeId(UUID.randomUUID());
edge = new Edge(edgeId);
edge.setTenantId(tenantId);
edge.setName("test-edge");
EdgeEventStorageSettings storageSettings = new EdgeEventStorageSettings();
ReflectionTestUtils.setField(storageSettings, "noRecordsSleepInterval", NO_RECORDS_SLEEP_INTERVAL_MS);
GrpcCallbackExecutorService grpcCallbackExecutorService = mock(GrpcCallbackExecutorService.class);
// run future callbacks inline so the re-arm is observable without waiting on a pool
doAnswer(invocation -> {
invocation.getArgument(0, Runnable.class).run();
return null;
}).when(grpcCallbackExecutorService).execute(any());
EdgeContextComponent ctx = mock(EdgeContextComponent.class);
when(ctx.getEdgeEventStorageSettings()).thenReturn(storageSettings);
when(ctx.getGrpcCallbackExecutorService()).thenReturn(grpcCallbackExecutorService);
when(ctx.getRuleProcessor()).thenReturn(mock(NotificationRuleProcessor.class));
TbServiceInfoProvider serviceInfoProvider = mock(TbServiceInfoProvider.class);
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
edgeIdServiceIdCache = mock(TbTransactionalCache.class);
// this node is the recorded owner of the edge, which is what a live local session implies
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE));
edgeEventProcessingExecutorService = Executors.newSingleThreadScheduledExecutor();
service = new EdgeGrpcService();
ReflectionTestUtils.setField(service, "ctx", ctx);
ReflectionTestUtils.setField(service, "tsSubService", mock(TelemetrySubscriptionService.class));
ReflectionTestUtils.setField(service, "clusterService", mock(TbClusterService.class));
ReflectionTestUtils.setField(service, "serviceInfoProvider", serviceInfoProvider);
ReflectionTestUtils.setField(service, "edgeIdServiceIdCache", edgeIdServiceIdCache);
ReflectionTestUtils.setField(service, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService);
}
@AfterEach
void tearDown() {
edgeEventProcessingExecutorService.shutdownNow();
}
@Test
void checkIsArmedForTheCurrentSession() {
EdgeGrpcSession session = newSession();
sessions().put(edgeId, session);
scheduleEdgeEventsCheck(session);
ScheduledFuture<?> armed = edgeEventChecks().get(edgeId);
assertThat((Object) armed).as("check armed for the session that owns the edge").isNotNull();
assertThat(armed.isCancelled()).isFalse();
}
@Test
void checkIsNotArmedForASupersededSession() {
EdgeGrpcSession current = newSession();
EdgeGrpcSession superseded = newSession();
sessions().put(edgeId, current);
scheduleEdgeEventsCheck(current);
ScheduledFuture<?> armedByCurrent = edgeEventChecks().get(edgeId);
scheduleEdgeEventsCheck(superseded);
assertThat((Object) edgeEventChecks().get(edgeId))
.as("the superseded session must neither cancel nor replace the current session's check")
.isSameAs(armedByCurrent);
assertThat(armedByCurrent.isCancelled()).isFalse();
}
@Test
void disconnectOfTheCurrentSessionDetachesItAndCancelsItsCheck() {
EdgeGrpcSession session = newSession();
onEdgeConnect(session);
ScheduledFuture<?> armedCheck = edgeEventChecks().get(edgeId);
onEdgeDisconnect(session);
assertThat(sessions()).doesNotContainKey(edgeId);
assertThat(sessionsById()).doesNotContainKey(session.getSessionId());
assertThat(armedCheck.isCancelled()).as("the detached session's check is cancelled").isTrue();
verify(edgeIdServiceIdCache).evict(edgeId);
verify(session).destroy();
}
@Test
void disconnectOfASupersededSessionKeepsTheReconnectedSessionAndItsCheck() {
EdgeGrpcSession first = newSession();
onEdgeConnect(first);
// the edge reconnects before the gRPC stream of the first session is closed
EdgeGrpcSession second = newSession();
onEdgeConnect(second);
ScheduledFuture<?> armedBySecond = edgeEventChecks().get(edgeId);
onEdgeDisconnect(first);
assertThat(sessions().get(edgeId)).as("the reconnected session stays registered").isSameAs(second);
assertThat(sessionsById()).containsKey(second.getSessionId());
assertThat((Object) edgeEventChecks().get(edgeId))
.as("the check armed by the reconnected session survives the teardown of the one it replaced")
.isSameAs(armedBySecond);
assertThat(armedBySecond.isCancelled()).isFalse();
verify(edgeIdServiceIdCache, never()).evict(edgeId);
}
@Test
void disconnectDoesNotClearTheNewEventsFlag() {
EdgeGrpcSession session = newSession();
onEdgeConnect(session);
assertThat(newEvents()).containsEntry(edgeId, true);
onEdgeDisconnect(session);
assertThat(newEvents())
.as("clearing the flag here would wipe the one a reconnecting session has just raised")
.containsEntry(edgeId, true);
}
@Test
void checkOfTheCurrentSessionConsumesTheFlagAndReArms() throws Exception {
EdgeGrpcSession session = newSession();
when(session.processEdgeEvents()).thenReturn(Futures.immediateFuture(false));
sessions().put(edgeId, session);
newEvents().put(edgeId, true);
migrationProcessed().put(edgeId, Boolean.TRUE);
processEvents(session);
assertThat(newEvents()).containsEntry(edgeId, false);
verify(session).processHighPriorityEvents();
verify(session).processEdgeEvents();
assertThat((Object) edgeEventChecks().get(edgeId)).as("the check re-arms itself").isNotNull();
}
@Test
void checkOfASupersededSessionLeavesTheFlagForTheSessionThatOwnsTheEdge() throws Exception {
EdgeGrpcSession superseded = newSession();
EdgeGrpcSession current = newSession();
sessions().put(edgeId, current);
newEvents().put(edgeId, true);
migrationProcessed().put(edgeId, Boolean.TRUE);
// cancel(true) cannot stop a check that has already started, so it runs against the old session
processEvents(superseded);
assertThat(newEvents())
.as("consuming the flag here would leave the reconnected session with nothing to fetch")
.containsEntry(edgeId, true);
verify(superseded, never()).processHighPriorityEvents();
verify(superseded, never()).processEdgeEvents();
assertThat(edgeEventChecks()).doesNotContainKey(edgeId);
}
@Test
void zombieCleanupCancelsTheCheckOfTheSessionItRemoves() {
KafkaEdgeGrpcSession zombie = newZombieSession();
when(zombie.destroy()).thenReturn(true);
sessions().put(edgeId, zombie);
scheduleEdgeEventsCheck(zombie);
ScheduledFuture<?> armedByZombie = edgeEventChecks().get(edgeId);
cleanupZombieSessions();
assertThat(sessions()).doesNotContainKey(edgeId);
assertThat(armedByZombie.isCancelled())
.as("the removed zombie must not leave an armed check behind")
.isTrue();
}
@Test
void zombieCleanupKeepsASessionThatReconnectedDuringTheSweep() {
KafkaEdgeGrpcSession zombie = newZombieSession();
EdgeGrpcSession reconnected = newSession();
sessions().put(edgeId, zombie);
// the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up
when(zombie.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, reconnected);
scheduleEdgeEventsCheck(reconnected);
return true;
});
cleanupZombieSessions();
assertThat(sessions().get(edgeId)).isSameAs(reconnected);
ScheduledFuture<?> armedByReconnected = edgeEventChecks().get(edgeId);
assertThat((Object) armedByReconnected).as("the reconnected session keeps its check").isNotNull();
assertThat(armedByReconnected.isCancelled()).isFalse();
}
private EdgeGrpcSession newSession() {
EdgeGrpcSession session = mock(EdgeGrpcSession.class);
stubSession(session);
return session;
}
private KafkaEdgeGrpcSession newZombieSession() {
KafkaEdgeGrpcSession session = mock(KafkaEdgeGrpcSession.class);
stubSession(session);
@SuppressWarnings("unchecked")
QueueConsumerManager<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class);
@SuppressWarnings("unchecked")
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class);
when(consumerManager.getConsumer()).thenReturn(consumer);
when(consumer.isStopped()).thenReturn(false);
when(session.getConsumer()).thenReturn(consumerManager);
return session;
}
private void stubSession(EdgeGrpcSession session) {
when(session.getEdge()).thenReturn(edge);
when(session.getTenantId()).thenReturn(tenantId);
when(session.getSessionId()).thenReturn(UUID.randomUUID());
when(session.isConnected()).thenReturn(false);
when(session.destroy()).thenReturn(true);
}
private void onEdgeConnect(EdgeGrpcSession session) {
ReflectionTestUtils.invokeMethod(service, "onEdgeConnect", edgeId, session);
}
private void onEdgeDisconnect(EdgeGrpcSession session) {
ReflectionTestUtils.invokeMethod(service, "onEdgeDisconnect", edge, session.getSessionId());
}
private void scheduleEdgeEventsCheck(EdgeGrpcSession session) {
ReflectionTestUtils.invokeMethod(service, "scheduleEdgeEventsCheck", session);
}
private void processEvents(EdgeGrpcSession session) {
ReflectionTestUtils.invokeMethod(service, "processEvents", session, edgeId, tenantId);
}
private void cleanupZombieSessions() {
ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions");
}
private ConcurrentMap<EdgeId, EdgeGrpcSession> sessions() {
return field("sessions");
}
private ConcurrentMap<UUID, EdgeGrpcSession> sessionsById() {
return field("sessionsById");
}
private ConcurrentMap<EdgeId, ScheduledFuture<?>> edgeEventChecks() {
return field("sessionEdgeEventChecks");
}
private Map<EdgeId, Boolean> newEvents() {
return field("sessionNewEvents");
}
private ConcurrentMap<EdgeId, Boolean> migrationProcessed() {
return field("edgeEventsMigrationProcessed");
}
@SuppressWarnings("unchecked")
private <T> T field(String name) {
return (T) ReflectionTestUtils.getField(service, name);
}
}

191
application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java

@ -22,10 +22,6 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor;
import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg;
import org.thingsboard.server.queue.TbQueueConsumer;
import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.common.consumer.QueueConsumerManager;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import org.thingsboard.server.service.edge.EdgeContextComponent;
@ -36,12 +32,12 @@ import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.argThat;
@ -164,17 +160,14 @@ public class EdgeGrpcServiceTest {
@Test
public void givenSessionReplacedDuringDisconnect_whenStaleCallbackRuns_thenLiveSessionKept() {
// Reproduces the get()/remove() interleaving on a single node: onEdgeConnect swaps in a new session
// right after the stale callback's id check passes. The stale callback must not evict or tear down
// the live session, nor clear the activity state.
// onEdgeConnect has already swapped in a new session on this node when the stale callback runs.
// The check-and-remove is a single atomic step against the same map that onEdgeConnect writes
// through, so the swap can only land before or after it. The stale callback must not evict or
// tear down the live session, nor clear the activity state.
UUID staleSessionId = UUID.randomUUID();
EdgeGrpcSession live = mock(EdgeGrpcSession.class);
EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
when(stale.getSessionId()).thenAnswer(invocation -> {
sessions().put(edgeId, live);
return staleSessionId;
});
sessions().put(edgeId, stale);
when(live.getSessionId()).thenReturn(UUID.randomUUID());
sessions().put(edgeId, live);
onEdgeDisconnect(staleSessionId);
@ -183,21 +176,11 @@ public class EdgeGrpcServiceTest {
}
@Test
public void givenSessionReplacedOnThisNodeAfterRemoval_whenStaleCallbackRuns_thenNoDisconnectSideEffects() {
// The stale callback wins the compare-and-remove, then tearing its own session down takes a while
// (for the Kafka session this stops a consumer). The edge reconnects to THIS node in that gap, so the
// ownership cache legitimately names us and isOwnedByAnotherNode cannot help. None of the disconnect
// side effects may run: not the flag, not the timestamp, not the DISCONNECT_EVENT push.
public void givenSessionReplacedOnThisNodeDuringDisconnect_whenStaleCallbackRuns_thenNoDisconnectSideEffects() {
// the edge reconnects to this node after the stale session was detached, so the cache names this node
UUID sessionId = UUID.randomUUID();
EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
when(stale.getSessionId()).thenReturn(sessionId);
when(stale.getEdge()).thenReturn(edge);
when(stale.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, mock(EdgeGrpcSession.class));
return true;
});
lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor);
sessions().put(edgeId, stale);
sessions().put(edgeId, sessionFor(sessionId));
reconnectToThisNodeOnOwnershipCheck();
onEdgeDisconnect(sessionId);
@ -208,132 +191,63 @@ public class EdgeGrpcServiceTest {
}
@Test
public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenDisconnectEventNotPushed() {
// The DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE, so a rule chain wiring
// Disconnect Event -> Save Attributes would persist active=false back and re-create the bug.
EdgeSessionStub stub = registerSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE));
lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor);
onEdgeDisconnect(stub.sessionId());
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
}
@Test
public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenDisconnectEventPushed() {
// Also proves the never() assertions above are not vacuous: the push does happen on this path.
EdgeSessionStub stub = registerSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE));
when(ctx.getRuleProcessor()).thenReturn(ruleProcessor);
onEdgeDisconnect(stub.sessionId());
verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
}
@Test
public void givenSessionReplacedOnThisNode_whenStaleCallbackRuns_thenReplacementEdgeEventsCheckNotCancelled() {
// sessionEdgeEventChecks is keyed by edgeId, not by session, so the replacement's check sits under the
// same key as the one this callback is tearing down. The check loop only reschedules itself from inside
// the task, so cancelling it here would leave a connected edge with nothing to restart downlink
// delivery - the same silent stall this guard exists to prevent.
public void givenReconnectDuringInactiveWrite_whenDisconnect_thenAttachWaitsForTheWrite() throws Exception {
// a same-node reconnect racing the guard must be ordered after the inactive write, so its active=true wins
UUID sessionId = UUID.randomUUID();
EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
when(stale.getSessionId()).thenReturn(sessionId);
when(stale.getEdge()).thenReturn(edge);
ScheduledFuture<?> replacementCheck = mock(ScheduledFuture.class);
when(stale.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, mock(EdgeGrpcSession.class));
sessionEdgeEventChecks().put(edgeId, replacementCheck);
return true;
});
sessions().put(edgeId, stale);
sessions().put(edgeId, sessionFor(sessionId));
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null);
EdgeGrpcSession replacement = mock(EdgeGrpcSession.class);
Thread attach = new Thread(() -> ReflectionTestUtils.invokeMethod(edgeGrpcService, "attachSession", edgeId, replacement));
AtomicBoolean attachBlockedDuringWrite = new AtomicBoolean();
lenient().doAnswer(invocation -> {
attach.start();
attach.join(200);
attachBlockedDuringWrite.set(attach.isAlive());
return null;
}).when(tsSubService).saveAttributes(argThat(inactiveStateWrite()));
onEdgeDisconnect(sessionId);
attach.join(5000);
verify(replacementCheck, never()).cancel(anyBoolean());
assertThat(sessionEdgeEventChecks()).containsEntry(edgeId, replacementCheck);
assertThat(attachBlockedDuringWrite).isTrue();
assertThat(sessions()).containsEntry(edgeId, replacement);
verify(tsSubService, times(1)).saveAttributes(argThat(lastDisconnectTimeWrite()));
}
@Test
public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenEdgeEventsCheckCancelled() {
// Counterpart to the test above: proves the cancel still runs on a real disconnect, so the guard is
// not simply disabling it.
public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenDisconnectEventNotPushed() {
// DISCONNECT_EVENT carries active=false, a Save Attributes node would write it back
UUID sessionId = UUID.randomUUID();
sessions().put(edgeId, sessionFor(sessionId));
ScheduledFuture<?> check = mock(ScheduledFuture.class);
sessionEdgeEventChecks().put(edgeId, check);
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE));
onEdgeDisconnect(sessionId);
verify(check, times(1)).cancel(anyBoolean());
assertThat(sessionEdgeEventChecks()).doesNotContainKey(edgeId);
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
}
// --- zombie session cleanup ---
@Test
@SuppressWarnings("unchecked")
public void givenZombieSessionReplacedDuringDestroy_whenCleanupRuns_thenReplacementKept() {
// destroy() stops a Kafka consumer and is not instantaneous. If the edge reconnects in that gap, an
// unconditional sessions.remove(edgeId) would drop the live session, leaving a connected edge with no
// map entry - every downlink lookup then silently no-ops.
KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class);
when(zombie.getEdge()).thenReturn(edge);
when(zombie.isConnected()).thenReturn(false);
QueueConsumerManager<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class);
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class);
when(consumer.isStopped()).thenReturn(false);
when(consumerManager.getConsumer()).thenReturn(consumer);
when(zombie.getConsumer()).thenReturn(consumerManager);
EdgeGrpcSession replacement = mock(EdgeGrpcSession.class);
when(zombie.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, replacement);
return true;
});
sessions().put(edgeId, zombie);
ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions");
public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenDisconnectEventPushed() {
UUID sessionId = UUID.randomUUID();
sessions().put(edgeId, sessionFor(sessionId));
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE));
when(ctx.getRuleProcessor()).thenReturn(ruleProcessor);
assertThat(sessions()).containsEntry(edgeId, replacement);
}
onEdgeDisconnect(sessionId);
@Test
@SuppressWarnings("unchecked")
public void givenZombieSessionStillCurrent_whenCleanupRuns_thenItIsRemoved() {
// Counterpart: with no replacement, the compare-and-remove must still drop the zombie.
KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class);
when(zombie.getEdge()).thenReturn(edge);
when(zombie.isConnected()).thenReturn(false);
QueueConsumerManager<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class);
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class);
when(consumer.isStopped()).thenReturn(false);
when(consumerManager.getConsumer()).thenReturn(consumer);
when(zombie.getConsumer()).thenReturn(consumerManager);
when(zombie.destroy()).thenReturn(true);
sessions().put(edgeId, zombie);
ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions");
assertThat(sessions()).doesNotContainKey(edgeId);
verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
}
// --- onEdgeConnect ownership publish order ---
@Test
public void givenConnect_whenClaimingOwnership_thenCachePutHappensBeforeActiveStateWrite() {
// Load-bearing ordering: the previous node's onEdgeDisconnect reads this cache entry to decide whether
// to clear the flag, so the claim must be visible before active=true is written. Nothing else pins the
// order, and a tidy-up that groups the save(...) calls together would silently restore the race.
// the previous node reads this cache entry on disconnect, so the claim must be visible before active=true
EdgeGrpcSession session = mock(EdgeGrpcSession.class);
when(session.getSessionId()).thenReturn(UUID.randomUUID());
when(session.getEdge()).thenReturn(edge);
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(ctx.getRuleProcessor()).thenReturn(ruleProcessor);
when(ctx.getEdgeEventStorageSettings()).thenReturn(edgeEventStorageSettings);
ReflectionTestUtils.setField(edgeGrpcService, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService);
when(edgeEventProcessingExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
@ -379,13 +293,13 @@ public class EdgeGrpcServiceTest {
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId);
}
private EdgeSessionStub registerSession() {
UUID sessionId = UUID.randomUUID();
sessions().put(edgeId, sessionFor(sessionId));
return new EdgeSessionStub(sessionId);
}
private record EdgeSessionStub(UUID sessionId) {
// simulates a reconnect to this node landing after the stale session was detached, before the guard runs
private void reconnectToThisNodeOnOwnershipCheck() {
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenAnswer(invocation -> {
sessions().put(edgeId, mock(EdgeGrpcSession.class));
return SimpleTbCacheValueWrapper.wrap(THIS_NODE);
});
}
private ArgumentMatcher<AttributesSaveRequest> activeStateWrite() {
@ -408,11 +322,6 @@ public class EdgeGrpcServiceTest {
return (ConcurrentMap<EdgeId, EdgeGrpcSession>) ReflectionTestUtils.getField(edgeGrpcService, "sessions");
}
@SuppressWarnings("unchecked")
private ConcurrentMap<EdgeId, ScheduledFuture<?>> sessionEdgeEventChecks() {
return (ConcurrentMap<EdgeId, ScheduledFuture<?>>) ReflectionTestUtils.getField(edgeGrpcService, "sessionEdgeEventChecks");
}
private ArgumentMatcher<AttributesSaveRequest> inactiveStateWrite() {
return request -> request != null
&& edgeId.equals(request.getEntityId())

70
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -15,8 +15,8 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.security.model.SecurityUser;
@ -89,7 +89,7 @@ class DefaultIotHubServiceTest {
mockTenant();
String versionId = UUID.randomUUID().toString();
String itemId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "DASHBOARD", "Root", "1.0"));
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "RULE_CHAIN", "Root", "1.0"));
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
InstallPlan plan = service.resolveInstallPlan(user, versionId);
@ -107,7 +107,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId))
@ -129,7 +129,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenReturn(null);
@ -149,7 +149,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenThrow(new RuntimeException("boom"));
@ -280,7 +280,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
IotHubInstalledItem depItem = installedItem(UUID.randomUUID());
IotHubInstalledItem rootItem = installedItem(UUID.randomUUID());
DashboardInstalledItemDescriptor rootDescriptor = new DashboardInstalledItemDescriptor();
RuleChainInstalledItemDescriptor rootDescriptor = new RuleChainInstalledItemDescriptor();
rootItem.setDescriptor(rootDescriptor);
doReturn(depItem).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any());
doReturn(rootItem).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any());
@ -331,6 +331,64 @@ class DefaultIotHubServiceTest {
inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId());
}
@Test
void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() throws Exception {
mockTenant();
HttpServletRequest request = mock(HttpServletRequest.class);
String rootVersionId = UUID.randomUUID().toString();
InstallPlanEntry root = willInstall(rootVersionId, true);
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any());
InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request);
// the sentence around the failure belongs to the dialog, which localizes it
assertThat(result.getErrorMessage()).isEqualTo("install failed");
}
@Test
void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() throws Exception {
mockTenant();
HttpServletRequest request = mock(HttpServletRequest.class);
String depVersionId = UUID.randomUUID().toString();
String rootVersionId = UUID.randomUUID().toString();
InstallPlanEntry dep = willInstall(depVersionId, false);
InstallPlanEntry root = willInstall(rootVersionId, true);
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any());
InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request);
// the dialog names the failing dependency itself, from the entry it finds in the result
assertThat(result.getErrorMessage()).isEqualTo("install failed");
assertThat(result.getEntries()).anySatisfy(entry -> {
assertThat(entry.getName()).isEqualTo("Dep");
assertThat(entry.isRoot()).isFalse();
assertThat(entry.getErrorMessage()).isEqualTo("install failed");
});
verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any());
}
@Test
void installPlan_failureWithoutMessage_reportsTheExceptionType() throws Exception {
mockTenant();
HttpServletRequest request = mock(HttpServletRequest.class);
String rootVersionId = UUID.randomUUID().toString();
InstallPlanEntry root = willInstall(rootVersionId, true);
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
doThrow(new NullPointerException()).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any());
InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request);
// the dialog looks the failing entry up by its error message, so it must never be blank
assertThat(result.getErrorMessage()).isEqualTo("NullPointerException");
assertThat(result.getEntries()).allSatisfy(entry ->
assertThat(entry.getErrorMessage()).isEqualTo("NullPointerException"));
}
@Test
void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception {
mockTenant();

7
application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java

@ -148,10 +148,13 @@ public class JobManagerTest extends AbstractControllerTest {
int tasksCount = 200;
JobId jobId = submitJob(DummyJobConfiguration.builder()
.successfulTasksCount(tasksCount)
.taskProcessingTimeMs(50)
.taskProcessingTimeMs(TimeUnit.SECONDS.toMillis(30)) // keeps tasks in flight when the job is cancelled, whatever the partitioning strategy
.taskProcessingTimeoutMs(TimeUnit.SECONDS.toMillis(60))
.build()).getId();
Thread.sleep(500);
await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> {
assertThat(findJobById(jobId).getStatus()).isEqualTo(JobStatus.RUNNING);
});
cancelJob(jobId);
await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> {
Job job = findJobById(jobId);

205
application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java

@ -32,6 +32,7 @@ import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.common.msg.queue.TopicPartitionInfo;
import org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.edge.EdgeService;
import org.thingsboard.server.gen.transport.TransportProtos;
@ -42,6 +43,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;
@ -77,6 +79,8 @@ public class DefaultTbClusterServiceTest {
public static final String TRANSPORT = "transport";
public static final String UNKNOWN_SERVICE_ID = "not-a-cluster-member";
@MockitoBean
protected TbDeviceProfileCache deviceProfileCache;
@MockitoBean
@ -277,6 +281,7 @@ public class DefaultTbClusterServiceTest {
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
TransportProtos.RestApiCallResponseMsgProto responseMsgProto = TransportProtos.RestApiCallResponseMsgProto.getDefaultInstance();
TransportProtos.ToCoreNotificationMsg toCoreNotificationMsg = TransportProtos.ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build();
@ -291,6 +296,206 @@ public class DefaultTbClusterServiceTest {
assertThat(protoQueueMsgArgumentCaptorValue.getKey()).isNotNull();
assertThat(protoQueueMsgArgumentCaptorValue.getValue()).isEqualTo(toCoreNotificationMsg);
assertThat(protoQueueMsgArgumentCaptorValue.getHeaders().getData()).isEqualTo(new DefaultTbQueueMsgHeaders().getData());
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE);
}
@Test
public void testPushNotificationToCoreToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_CORE), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getTbCoreNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToCoreToRecentlySeenButOfflineServiceIdIsSent() {
String offlineCore = "core-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
// offlineCore was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineCore).addServiceTypes(ServiceType.TB_CORE.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(CORE).addServiceTypes(ServiceType.TB_CORE.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, offlineCore);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(offlineCore, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToCoreToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, CORE);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(CORE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE);
}
@Test
public void testPushNotificationToCoreFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToRuleEngineToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_RULE_ENGINE), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getRuleEngineNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToRuleEngineToRecentlySeenButOfflineServiceIdIsSent() {
String offlineRuleEngine = "rule-engine-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
// offlineRuleEngine was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineRuleEngine).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(RULE_ENGINE).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, offlineRuleEngine);
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(offlineRuleEngine, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToRuleEngineToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, RULE_ENGINE)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, RULE_ENGINE);
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(RULE_ENGINE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_RULE_ENGINE);
}
@Test
public void testPushNotificationToRuleEngineFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToTransportToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_TRANSPORT), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getTransportNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToTransportToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_TRANSPORT, TRANSPORT)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, TRANSPORT);
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(TRANSPORT, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_TRANSPORT);
}
@Test
public void testPushNotificationToTransportToRecentlySeenButOfflineServiceIdIsSent() {
String offlineTransport = "transport-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
// offlineTransport was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineTransport).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(TRANSPORT).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, offlineTransport);
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(offlineTransport, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToTransportFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test

86
application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java

@ -4,13 +4,17 @@ package org.thingsboard.server.service.script;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import delight.nashornsandbox.NashornSandbox;
import delight.nashornsandbox.NashornSandboxes;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.common.util.TbStopWatch;
import org.thingsboard.script.api.RuleNodeScriptFactory;
import org.thingsboard.script.api.ScriptType;
import org.thingsboard.script.api.TbScriptException;
import org.thingsboard.script.api.js.NashornJsInvokeService;
@ -18,6 +22,7 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.controller.AbstractControllerTest;
import org.thingsboard.server.dao.service.DaoSqlTest;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.ArrayList;
import java.util.List;
@ -209,6 +214,87 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest {
});
}
@Test
void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception {
UUID scriptId = evalScript("return msg;");
String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_');
assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(true);
invokeService.release(scriptId).get();
// the property must be deleted, not just set to undefined: an abandoned binding keeps
// its slot in the Global's PropertyMap forever
assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(false);
}
@Test
void givenIifeWrappedEval_whenInvoking_thenResultIsUnchanged() throws Exception {
UUID scriptId = evalScript("return {doubled: msg.temperature * 2};");
assertThat(invokeScript(scriptId, "{\"temperature\":21}")).contains("\"doubled\":42");
}
@Test
void givenIifeWrappedEval_thenImplicitGlobalStateIsStillSharedBetweenScripts() throws Exception {
UUID writer = evalScript("compatSharedState = 777; return msg;");
UUID reader = evalScript("return {seen: (typeof compatSharedState === 'undefined') ? null : compatSharedState};");
invokeScript(writer, "{}");
assertThat(invokeScript(reader, "{}")).contains("\"seen\":777");
}
@Test
void givenIifeWrappedEval_thenCompilationErrorUnchanged() {
String badScript = "var a = 1;\nvar b = 2;\nreturn msg.temperature?.value;";
String legacyScript = RuleNodeScriptFactory.generateRuleNodeScript("invokeInternal_legacy", badScript,
"msg", "metadata", "msgType");
NashornSandbox legacySandbox = NashornSandboxes.create();
legacySandbox.allowNoBraces(false);
legacySandbox.allowLoadFunctions(true);
legacySandbox.setMaxPreparedStatements(30);
int legacyErrorLine = -1;
try {
legacySandbox.eval(legacyScript);
} catch (ScriptException e) {
legacyErrorLine = e.getLineNumber();
}
assertThat(legacyErrorLine).isGreaterThan(0);
final int expectedLine = legacyErrorLine;
assertThatThrownBy(() -> evalScript(badScript))
.isInstanceOf(ExecutionException.class)
.cause()
.isInstanceOf(TbScriptException.class)
.asInstanceOf(type(TbScriptException.class))
.satisfies(ex -> {
assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.COMPILATION);
assertThat(ex.getBody()).contains(badScript);
assertThat(ex.getCause()).isInstanceOf(ScriptException.class);
// The IIFE wrapper shifts sandbox-reported line numbers by a constant +2
// (the beautifier splits the wrapper prefix onto its own lines). Reported
// lines never matched the user's source anyway (the sandbox instrumentation
// already offsets them), so only the small constant shift is tolerated here.
assertThat(((ScriptException) ex.getCause()).getLineNumber()).isBetween(expectedLine, expectedLine + 2);
});
}
@Test
void whenInvokingAfterRelease_thenFailsWithNoCompiledScriptFound() throws Exception {
UUID scriptId = evalScript("return msg;");
invokeScript(scriptId, "{}");
invokeService.release(scriptId).get();
assertThatThrownBy(() -> invokeScript(scriptId, "{}"))
.isInstanceOf(ExecutionException.class)
.hasMessageContaining("No compiled script found");
}
private Object evalInEngine(String expression) throws Exception {
Object sandbox = ReflectionTestUtils.getField(invokeService, "sandbox");
if (sandbox != null) {
return ((NashornSandbox) sandbox).eval(expression);
}
return ((ScriptEngine) ReflectionTestUtils.getField(invokeService, "engine")).eval(expression);
}
private void assertThatScriptIsBlocked(UUID scriptId) {
assertThatThrownBy(() -> {
invokeScript(scriptId, "{}");

14
application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java

@ -288,6 +288,20 @@ class TbelInvokeServiceTest extends AbstractTbelInvokeTest {
});
}
@Test
void givenForbiddenFormatter_whenInvoking_thenThrowsRuntimeError() throws ExecutionException, InterruptedException {
UUID scriptId = evalScript("new java.util.Formatter(\"/tmp/test.txt\")");
assertThatThrownBy(() -> invokeScript(scriptId, "{\"temperature\":25}"))
.isInstanceOf(ExecutionException.class)
.cause()
.isInstanceOf(TbScriptException.class)
.asInstanceOf(type(TbScriptException.class))
.satisfies(ex -> {
assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.RUNTIME);
assertThat(ex.getCause().getMessage()).contains("could not resolve class: java.util.Formatter");
});
}
private void assertThatScriptIsBlocked(UUID scriptId) {
assertThatThrownBy(() -> {
invokeScriptResultString(scriptId, "{}");

45
application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java

@ -1,45 +0,0 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME;
public class CookieUtilsTest {
@Test
public void serializeDeserializeOAuth2AuthorizationRequestTest() {
HttpCookieOAuth2AuthorizationRequestRepository cookieRequestRepo = new HttpCookieOAuth2AuthorizationRequestRepository();
HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
Map<String, Object> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
var request = OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("testUri").clientId("testId")
.scope("read", "write")
.additionalParameters(additionalParameters).build();
Cookie cookie = new Cookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(request));
Mockito.when(servletRequest.getCookies()).thenReturn(new Cookie[]{cookie});
OAuth2AuthorizationRequest deserializedRequest = cookieRequestRepo.loadAuthorizationRequest(servletRequest);
assertNotNull(deserializedRequest);
assertEquals(request.getGrantType(), deserializedRequest.getGrantType());
assertEquals(request.getAuthorizationUri(), deserializedRequest.getAuthorizationUri());
assertEquals(request.getClientId(), deserializedRequest.getClientId());
}
}

151
application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java

@ -2,27 +2,50 @@
// 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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.thingsboard.server.common.data.security.model.JwtSettings;
import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService;
import java.security.SecureRandom;
import java.time.Clock;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_COOKIE_NAME;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_PARAMETER;
public class HttpCookieOAuth2AuthorizationRequestRepositoryTest {
private final HttpCookieOAuth2AuthorizationRequestRepository repository = new HttpCookieOAuth2AuthorizationRequestRepository();
private static final long NOW = 1_700_000_000_000L;
private final JwtSettingsService jwtSettingsService = mock(JwtSettingsService.class);
private final Clock clock = mock(Clock.class);
private final HttpCookieOAuth2AuthorizationRequestRepository repository =
new HttpCookieOAuth2AuthorizationRequestRepository(jwtSettingsService, clock);
@BeforeEach
public void before() {
givenSigningKey(randomSigningKey());
when(clock.millis()).thenReturn(NOW);
}
@Test
public void testPrevUriSavedForInAppPath() {
@ -37,20 +60,140 @@ public class HttpCookieOAuth2AuthorizationRequestRepositoryTest {
assertThat(savePrevUri(prevUri)).isNull();
}
@Test
public void testAuthorizationRequestRoundTrip() {
Map<String, Object> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("testUri").clientId("testId")
.scope("read", "write")
.state("testState")
.additionalParameters(additionalParameters)
.attributes(attributes -> attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, "tbmobile"))
.build();
OAuth2AuthorizationRequest loaded = load(save(authorizationRequest));
assertThat(loaded).isNotNull();
assertThat(loaded.getGrantType()).isEqualTo(authorizationRequest.getGrantType());
assertThat(loaded.getAuthorizationUri()).isEqualTo(authorizationRequest.getAuthorizationUri());
assertThat(loaded.getClientId()).isEqualTo(authorizationRequest.getClientId());
assertThat(loaded.getScopes()).isEqualTo(authorizationRequest.getScopes());
assertThat(loaded.getState()).isEqualTo(authorizationRequest.getState());
assertThat(loaded.getAdditionalParameters()).isEqualTo(additionalParameters);
assertThat(CallbackUrlSchemeValidator.getCallbackUrlScheme(loaded)).isEqualTo("tbmobile");
}
@Test
public void testCookieIsNotPlainJson() {
String cookieValue = save(authorizationRequest());
assertThat(new String(Base64.getUrlDecoder().decode(cookieValue))).doesNotContain("testId");
}
@Test
public void testEachCookieUsesFreshNonce() {
assertThat(save(authorizationRequest())).isNotEqualTo(save(authorizationRequest()));
}
@Test
public void testTamperedCookieIsRejected() {
byte[] envelope = Base64.getUrlDecoder().decode(save(authorizationRequest()));
for (int i = 0; i < envelope.length; i++) {
byte[] tampered = envelope.clone();
tampered[i] ^= 0x01;
assertThat(load(Base64.getUrlEncoder().withoutPadding().encodeToString(tampered))).as("bit flipped at byte %s", i).isNull();
}
}
@Test
public void testTruncatedCookieIsRejected() {
String cookieValue = save(authorizationRequest());
assertThat(load(cookieValue.substring(0, cookieValue.length() - 4))).isNull();
}
@Test
public void testCookieEncryptedWithDifferentKeyIsRejected() {
String cookieValue = save(authorizationRequest());
givenSigningKey(randomSigningKey());
assertThat(load(cookieValue)).isNull();
}
@Test
public void testNewCookieIsAcceptedAfterKeyRotation() {
givenSigningKey(randomSigningKey());
String cookieValue = save(authorizationRequest());
assertThat(load(cookieValue)).isNotNull();
}
@Test
public void testUnencryptedCookieIsRejected() throws Exception {
ObjectMapper mapper = new ObjectMapper().registerModules(SecurityJackson2Modules.getModules(getClass().getClassLoader()));
String plainCookieValue = Base64.getUrlEncoder().encodeToString(mapper.writeValueAsBytes(authorizationRequest()));
assertThat(load(plainCookieValue)).isNull();
}
@ParameterizedTest
@ValueSource(strings = {"", "a", "AAAA", "not base64 !", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"})
public void testMalformedCookieIsRejected(String cookieValue) {
assertThat(load(cookieValue)).isNull();
}
@Test
public void testExpiredCookieIsRejected() {
String cookieValue = save(authorizationRequest());
when(clock.millis()).thenReturn(NOW + 180_000);
assertThat(load(cookieValue)).isNotNull();
when(clock.millis()).thenReturn(NOW + 180_001);
assertThat(load(cookieValue)).isNull();
}
private OAuth2AuthorizationRequest authorizationRequest() {
return OAuth2AuthorizationRequest.authorizationCode().authorizationUri("testUri").clientId("testId").build();
}
private String save(OAuth2AuthorizationRequest authorizationRequest) {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
repository.saveAuthorizationRequest(authorizationRequest, request, response);
return findCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME);
}
private OAuth2AuthorizationRequest load(String cookieValue) {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getCookies()).thenReturn(new Cookie[]{new Cookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, cookieValue)});
return repository.loadAuthorizationRequest(request);
}
private String savePrevUri(String prevUri) {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter(PREV_URI_PARAMETER)).thenReturn(prevUri);
repository.saveAuthorizationRequest(OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("testUri").clientId("testId").build(), request, response);
repository.saveAuthorizationRequest(authorizationRequest(), request, response);
return findCookie(response, PREV_URI_COOKIE_NAME);
}
private String findCookie(HttpServletResponse response, String name) {
ArgumentCaptor<Cookie> cookieCaptor = ArgumentCaptor.forClass(Cookie.class);
verify(response, atLeastOnce()).addCookie(cookieCaptor.capture());
return cookieCaptor.getAllValues().stream()
.filter(cookie -> PREV_URI_COOKIE_NAME.equals(cookie.getName()))
.filter(cookie -> name.equals(cookie.getName()))
.map(Cookie::getValue)
.findAny().orElse(null);
}
private void givenSigningKey(String signingKey) {
JwtSettings jwtSettings = new JwtSettings();
jwtSettings.setTokenSigningKey(signingKey);
when(jwtSettingsService.getJwtSettings()).thenReturn(jwtSettings);
}
private static String randomSigningKey() {
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
return Base64.getEncoder().encodeToString(key);
}
}

294
application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java

@ -0,0 +1,294 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.solutions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.DashboardInfo;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.asset.AssetProfile;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.common.data.rule.RuleChainType;
import org.thingsboard.server.dao.asset.AssetProfileService;
import org.thingsboard.server.dao.asset.AssetService;
import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.edge.EdgeService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.service.solutions.data.SolutionValidationResult;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class DefaultSolutionServiceTest {
private static final String CONFLICTS_INTRO =
"Some entities of the solution template already exist. Rename or delete them and install the template again:";
// mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it
private static final int LISTED_NAMES_PER_TYPE = 10;
private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE
+ " names of each type are listed. The rest are reported the next time the template is installed.";
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
@Mock
private CustomerService customerService;
@Mock
private DeviceService deviceService;
@Mock
private AssetService assetService;
@Mock
private DashboardService dashboardService;
@Mock
private RuleChainService ruleChainService;
@Mock
private DeviceProfileService deviceProfileService;
@Mock
private AssetProfileService assetProfileService;
@Mock
private EdgeService edgeService;
@InjectMocks
private DefaultSolutionService service;
@TempDir
private Path tempDir;
@Test
void testValidateSolutionNamesEveryConflictingEntity() throws IOException {
writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]");
writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]");
writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]");
Customer customer = new Customer();
customer.setTitle("Existing customer");
when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer));
Asset asset = new Asset();
asset.setName("Existing asset");
when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset);
when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null);
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device"))
.thenReturn(existingDevice("Existing device"));
when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null);
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
assertThat(result.isPassed()).isFalse();
assertThat(result.getConflictReport().lines().toList())
.containsSubsequence(
CONFLICTS_INTRO,
"- **Customer**: 'Existing customer'",
"- **Asset**: 'Existing asset'",
"- **Device**: 'Existing device'");
// the randomized customer title and the entities that do not exist yet are not reported
assertThat(result.getConflictReport())
.doesNotContain("Customer $random")
.doesNotContain("New device")
.doesNotContain("New asset");
}
@Test
void testValidateSolutionReportsConflictingDashboard() throws IOException {
writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]");
DashboardInfo dashboard = new DashboardInfo();
dashboard.setTitle("Overview");
when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard);
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
assertThat(result.isPassed()).isFalse();
assertThat(result.getConflictReport().lines().toList())
.containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'");
}
@Test
void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException {
writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]");
writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}");
RuleChain ruleChain = new RuleChain();
ruleChain.setName("Name the install creates");
when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates"))
.thenReturn(List.of(ruleChain));
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
assertThat(result.isPassed()).isFalse();
assertThat(result.getConflictReport().lines().toList())
.containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'");
}
@Test
void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException {
writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]");
writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]");
writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]");
DeviceProfile deviceProfile = new DeviceProfile();
deviceProfile.setName("thermostat");
AssetProfile assetProfile = new AssetProfile();
assetProfile.setName("building");
Edge edge = new Edge();
edge.setName("Main edge");
when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile);
when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile);
when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge);
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
assertThat(result.isPassed()).isFalse();
assertThat(result.getConflictReport().lines().toList()).containsSubsequence(
"- **Device profile**: 'thermostat'",
"- **Asset profile**: 'building'",
"- **Edge**: 'Main edge'");
}
@Test
void testValidateSolutionLooksTheSameNameUpOnce() throws IOException {
writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]");
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor"));
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'");
verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor");
}
@Test
void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException {
writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," +
"{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]");
writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}");
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue();
verifyNoInteractions(ruleChainService);
}
@Test
void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException {
writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]");
writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}");
RuleChain ruleChain = new RuleChain();
ruleChain.setName("Edge chain");
when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain"))
.thenReturn(List.of(ruleChain));
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'");
}
@Test
void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException {
writeEntitiesFile("devices.json", "null");
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue();
verifyNoInteractions(deviceService);
}
@ParameterizedTest
@ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2})
void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException {
List<String> names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList();
writeEntitiesFile("devices.json", names.stream()
.map(name -> "{\"name\": \"" + name + "\"}")
.collect(Collectors.joining(",", "[", "]")));
names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name))
.thenReturn(existingDevice(name)));
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
int hidden = conflictCount - LISTED_NAMES_PER_TYPE;
String listed = names.stream().limit(LISTED_NAMES_PER_TYPE)
.map(name -> "'" + name + "'").collect(Collectors.joining(", "));
assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed
+ (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : ""));
if (hidden > 0) {
assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE);
} else {
assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE);
}
}
/**
* The profile lists are the json file plus every file in the directory of the same name merged into one list, so
* this is where the same name genuinely can appear twice.
*/
@Test
void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException {
writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]");
writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}");
DeviceProfile profile = new DeviceProfile();
profile.setName("Sensor profile");
when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile);
SolutionValidationResult result = service.validateSolution(tenantId, tempDir);
assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'");
verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile");
}
@Test
void testValidateSolutionWithoutConflicts() throws IOException {
writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]");
when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null);
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue();
}
@Test
void testValidateSolutionWithoutEntityFiles() {
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue();
verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService,
deviceProfileService, assetProfileService, edgeService);
}
private static Device existingDevice(String name) {
Device device = new Device();
device.setName(name);
return device;
}
private void writeFile(String relativePath, String content) throws IOException {
Path file = tempDir.resolve(relativePath);
Files.createDirectories(file.getParent());
Files.writeString(file, content);
}
private void writeEntitiesFile(String fileName, String content) throws IOException {
Path entitiesDir = Files.createDirectories(tempDir.resolve("entities"));
Files.writeString(entitiesDir.resolve(fileName), content);
}
}

2
common/actor/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/cache/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/cluster-api/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/coap-server/pom.xml

@ -11,7 +11,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

6
common/dao-api/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>
@ -41,6 +41,10 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>

2
common/data/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

13
common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java

@ -1,13 +0,0 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.common.data.iot_hub;
import lombok.Data;
import org.thingsboard.server.common.data.id.DashboardId;
@Data
public class DashboardInstalledItemDescriptor implements IotHubInstalledItemDescriptor {
private DashboardId dashboardId;
}

1
common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java

@ -15,7 +15,6 @@ import java.io.Serializable;
property = "type")
@JsonSubTypes({
@Type(name = "WIDGET", value = WidgetInstalledItemDescriptor.class),
@Type(name = "DASHBOARD", value = DashboardInstalledItemDescriptor.class),
@Type(name = "CALCULATED_FIELD", value = CalculatedFieldInstalledItemDescriptor.class),
@Type(name = "ALARM_RULE", value = AlarmRuleInstalledItemDescriptor.class),
@Type(name = "RULE_CHAIN", value = RuleChainInstalledItemDescriptor.class),

11
common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java

@ -15,11 +15,16 @@ public enum RpcStatus {
FAILED(false),
DELETED(false);
/**
* {@code true} while the RPC is still pending in the device actor (not yet delivered/answered).
* Note: TIMEOUT is not intermediate, but it is not final either - the device actor may retry
* the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED) until retries are exhausted (then FAILED).
*/
@Getter
private final boolean pushDeleteNotificationToCore;
private final boolean intermediate;
RpcStatus(boolean pushDeleteNotificationToCore) {
this.pushDeleteNotificationToCore = pushDeleteNotificationToCore;
RpcStatus(boolean intermediate) {
this.intermediate = intermediate;
}
}

10
common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java

@ -13,20 +13,20 @@ import static org.thingsboard.server.common.data.rpc.RpcStatus.SENT;
class RpcStatusTest {
private static final List<RpcStatus> pushDeleteNotificationToCoreStatuses = List.of(
private static final List<RpcStatus> intermediateStatuses = List.of(
QUEUED,
SENT,
DELIVERED
);
@Test
void isPushDeleteNotificationToCoreStatusTest() {
void isIntermediateStatusTest() {
var rpcStatuses = RpcStatus.values();
for (var status : rpcStatuses) {
if (pushDeleteNotificationToCoreStatuses.contains(status)) {
assertThat(status.isPushDeleteNotificationToCore()).isTrue();
if (intermediateStatuses.contains(status)) {
assertThat(status.isIntermediate()).isTrue();
} else {
assertThat(status.isPushDeleteNotificationToCore()).isFalse();
assertThat(status.isIntermediate()).isFalse();
}
}
}

2
common/discovery-api/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/edge-api/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/edge-api/src/main/proto/edge.proto

@ -39,6 +39,7 @@ enum EdgeVersion {
V_4_2_2_4 = 4224;
V_4_2_2_5 = 4225;
V_4_2_2_6 = 4226;
V_4_2_2_7 = 4227;
V_LATEST = 99999;
}
@ -380,6 +381,7 @@ message DeviceRpcCallMsg {
optional string additionalInfo = 12;
optional string serviceId = 13;
optional string sessionId = 14;
optional string rpcStatus = 15;
}
message RpcRequestMsg {

2
common/edqs/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/message/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>thingsboard</artifactId>
</parent>
<artifactId>common</artifactId>

2
common/proto/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

7
common/queue/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>
@ -123,6 +123,11 @@
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

19
common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java

@ -96,7 +96,7 @@ public class HashPartitionService implements PartitionService {
private final ConcurrentMap<TenantId, TenantRoutingInfo> tenantRoutingInfoMap = new ConcurrentHashMap<>();
private List<ServiceInfo> currentOtherServices;
private volatile List<ServiceInfo> currentOtherServices;
private final Map<String, List<ServiceInfo>> tbTransportServicesByType = new HashMap<>();
private volatile Map<TenantProfileId, List<ServiceInfo>> responsibleServices = Collections.emptyMap();
@ -537,6 +537,23 @@ public class HashPartitionService implements PartitionService {
return getAllServices(serviceType).stream().map(ServiceInfo::getServiceId).collect(Collectors.toSet());
}
@Override
public boolean isKnownServiceId(ServiceType serviceType, String serviceId) {
ServiceInfo current = serviceInfoProvider.getServiceInfo();
if (serviceId.equals(current.getServiceId()) && current.getServiceTypesList().contains(serviceType.name())) {
return true;
}
List<ServiceInfo> others = currentOtherServices;
if (others != null) {
for (ServiceInfo serviceInfo : others) {
if (serviceId.equals(serviceInfo.getServiceId()) && serviceInfo.getServiceTypesList().contains(serviceType.name())) {
return true;
}
}
}
return false;
}
@Override
public Set<ServiceInfo> getAllServices(ServiceType serviceType) {
Set<ServiceInfo> result = getOtherServices(serviceType);

6
common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java

@ -48,6 +48,12 @@ public interface PartitionService {
*/
Set<String> getAllServiceIds(ServiceType serviceType);
/**
* Cheaper alternative to {@link #getAllServiceIds} when only membership of a single id needs to be checked -
* avoids building the full service id set.
*/
boolean isKnownServiceId(ServiceType serviceType, String serviceId);
Set<TransportProtos.ServiceInfo> getAllServices(ServiceType serviceType);
Set<TransportProtos.ServiceInfo> getOtherServices(ServiceType serviceType);

100
common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java

@ -20,7 +20,7 @@ import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryForever;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
@ -32,12 +32,14 @@ import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.queue.discovery.event.OtherServiceShutdownEvent;
import org.thingsboard.server.queue.util.AfterStartUp;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.curator.framework.recipes.cache.CuratorCacheAccessor.parentPathFilter;
@ -103,20 +105,32 @@ public class ZkDiscoveryService implements DiscoveryService {
@Override
public List<TransportProtos.ServiceInfo> getOtherServers() {
String currentServiceId = serviceInfoProvider.getServiceInfo().getServiceId();
return cache.stream()
.filter(parentPathFilter(zkNodesDir))
.filter(cd -> !cd.getPath().equals(nodePath))
.map(cd -> {
try {
return TransportProtos.ServiceInfo.parseFrom(cd.getData());
return new Registration(cd, TransportProtos.ServiceInfo.parseFrom(cd.getData()));
} catch (NoSuchElementException | InvalidProtocolBufferException e) {
log.error("Failed to decode ZK node", e);
throw new RuntimeException(e);
}
})
.filter(r -> !r.info().getServiceId().equals(currentServiceId))
// Orders ZK registrations by creation, so that a re-registration wins over a stale node of the same service.
// Uses the creation zxid: ZooKeeper's transaction id, which grows across leader changes and is the same
// on every client. ctime/mtime are not used, as they come from the leader's wall clock and may go backwards.
.collect(Collectors.toMap(r -> r.info().getServiceId(), Function.identity(),
(a, b) -> b.data().getStat().getCzxid() > a.data().getStat().getCzxid() ? b : a,
LinkedHashMap::new))
.values().stream()
.map(Registration::info)
.collect(Collectors.toList());
}
private record Registration(ChildData data, TransportProtos.ServiceInfo info) {}
@Override
public boolean isMonolith() {
return false;
@ -146,21 +160,26 @@ public class ZkDiscoveryService implements DiscoveryService {
@SneakyThrows
public synchronized void publishCurrentServer() {
TransportProtos.ServiceInfo self = serviceInfoProvider.getServiceInfo();
if (currentServerExists()) {
log.trace("[{}] Updating ZK node for current instance: {}", self.getServiceId(), nodePath);
client.setData().forPath(nodePath, serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo().toByteArray());
} else {
try {
log.info("[{}] Creating ZK node for current instance", self.getServiceId());
nodePath = client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkNodesDir + "/", self.toByteArray());
log.info("[{}] Created ZK node for current instance: {}", self.getServiceId(), nodePath);
client.getConnectionStateListenable().addListener(checkReconnect(self));
} catch (Exception e) {
log.error("Failed to create ZK node", e);
throw new RuntimeException(e);
switch (getCurrentServerNodeState()) {
case PRESENT -> {
log.trace("[{}] Updating ZK node for current instance: {}", self.getServiceId(), nodePath);
client.setData().forPath(nodePath, serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo().toByteArray());
}
case ABSENT -> {
try {
log.info("[{}] Creating ZK node for current instance", self.getServiceId());
nodePath = client.create()
.creatingParentsIfNeeded()
.withProtection()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkNodesDir + "/node-", self.toByteArray());
log.info("[{}] Created ZK node for current instance: {}", self.getServiceId(), nodePath);
client.getConnectionStateListenable().addListener(checkReconnect(self));
} catch (Exception e) {
log.error("Failed to create ZK node", e);
throw new RuntimeException(e);
}
}
case UNKNOWN -> log.debug("[{}] Skipping ZK node publish, node state is unknown", self.getServiceId());
}
}
@ -177,23 +196,35 @@ public class ZkDiscoveryService implements DiscoveryService {
}
}
private boolean currentServerExists() {
private NodeState getCurrentServerNodeState() {
if (nodePath == null) {
return false;
return NodeState.ABSENT;
}
try {
TransportProtos.ServiceInfo self = serviceInfoProvider.getServiceInfo();
TransportProtos.ServiceInfo registeredServerInfo = null;
registeredServerInfo = TransportProtos.ServiceInfo.parseFrom(client.getData().forPath(nodePath));
if (self.equals(registeredServerInfo)) {
return true;
Stat stat = client.checkExists().forPath(nodePath);
if (stat == null) {
log.info("ZK node does not exist: {}", nodePath);
return NodeState.ABSENT;
}
} catch (KeeperException.NoNodeException e) {
log.info("ZK node does not exist: {}", nodePath);
long sessionId = client.getZookeeperClient().getZooKeeper().getSessionId();
if (stat.getEphemeralOwner() != sessionId) {
log.warn("ZK node {} is owned by another session 0x{}, current session 0x{}",
nodePath, Long.toHexString(stat.getEphemeralOwner()), Long.toHexString(sessionId));
return NodeState.ABSENT;
}
return NodeState.PRESENT;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("Interrupted while checking if ZK node exists", e);
return NodeState.UNKNOWN;
} catch (Exception e) {
log.error("Couldn't check if ZK node exists", e);
return NodeState.UNKNOWN;
}
return false;
}
private enum NodeState {
PRESENT, ABSENT, UNKNOWN
}
private ConnectionStateListener checkReconnect(TransportProtos.ServiceInfo self) {
@ -313,6 +344,14 @@ public class ZkDiscoveryService implements DiscoveryService {
String serviceId = instance.getServiceId();
ProtocolStringList serviceTypesList = instance.getServiceTypesList();
if (serviceId.equals(serviceInfoProvider.getServiceInfo().getServiceId())) {
if (type == CuratorCacheListener.Type.NODE_CREATED) {
log.error("[{}] Ignoring ZK node {} registered with the current service id. " +
"It is either a stale registration of this service or another service uses the same service id", serviceId, data.getPath());
}
return;
}
log.trace("Processing [{}] event for [{}]", type, serviceId);
switch (type) {
case NODE_CREATED:
@ -333,16 +372,19 @@ public class ZkDiscoveryService implements DiscoveryService {
}
break;
case NODE_DELETED:
if (getOtherServers().stream().anyMatch(s -> s.getServiceId().equals(serviceId))) {
log.debug("[{}] Ignoring removal of duplicate ZK node {}, service is still registered", serviceId, data.getPath());
break;
}
zkExecutorService.submit(() -> applicationEventPublisher.publishEvent(new OtherServiceShutdownEvent(this, serviceId, serviceTypesList)));
ScheduledFuture<?> future = zkExecutorService.schedule(() -> {
delayedTasks.compute(serviceId, (id, previous) -> zkExecutorService.schedule(() -> {
log.debug("[{}] Going to recalculate partitions due to removed node [{}]",
serviceId, serviceTypesList);
ScheduledFuture<?> removedTask = delayedTasks.remove(serviceId);
if (removedTask != null) {
recalculatePartitions();
}
}, recalculateDelay, TimeUnit.MILLISECONDS);
delayedTasks.put(serviceId, future);
}, recalculateDelay, TimeUnit.MILLISECONDS));
break;
default:
break;

189
common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java

@ -2,11 +2,19 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.queue.discovery;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CreateBuilder;
import org.apache.curator.framework.api.ExistsBuilder;
import org.apache.curator.framework.api.SetDataBuilder;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -17,6 +25,7 @@ import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.common.util.ThingsBoardExecutors;
import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.queue.discovery.event.OtherServiceShutdownEvent;
import java.util.ArrayList;
import java.util.Collections;
@ -29,6 +38,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
@ -56,6 +68,8 @@ public class ZkDiscoveryServiceTest {
private List<ChildData> dataList;
private static final long RECALCULATE_DELAY = 100L;
private static final long SESSION_ID = 0x100L;
private static final long OTHER_SESSION_ID = 0x200L;
final TransportProtos.ServiceInfo currentInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-rule-engine-0").build();
final ChildData currentData = new ChildData("/thingsboard/nodes/0000000010", null, currentInfo.toByteArray());
@ -66,7 +80,7 @@ public class ZkDiscoveryServiceTest {
public void setup() {
zkDiscoveryService = Mockito.spy(new ZkDiscoveryService(applicationEventPublisher, serviceInfoProvider, partitionService));
ScheduledExecutorService zkExecutorService = ThingsBoardExecutors.newSingleThreadScheduledExecutor("zk-discovery");
when(client.getState()).thenReturn(CuratorFrameworkState.STARTED);
lenient().when(client.getState()).thenReturn(CuratorFrameworkState.STARTED);
ReflectionTestUtils.setField(zkDiscoveryService, "stopped", false);
ReflectionTestUtils.setField(zkDiscoveryService, "client", client);
ReflectionTestUtils.setField(zkDiscoveryService, "cache", cache);
@ -76,11 +90,11 @@ public class ZkDiscoveryServiceTest {
ReflectionTestUtils.setField(zkDiscoveryService, "zkDir", "/thingsboard");
ReflectionTestUtils.setField(zkDiscoveryService, "zkNodesDir", "/thingsboard/nodes");
when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo);
lenient().when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo);
dataList = new ArrayList<>();
dataList.add(currentData);
when(cache.stream()).thenAnswer(inv -> dataList.stream());
lenient().when(cache.stream()).thenAnswer(inv -> dataList.stream());
}
@Test
@ -164,6 +178,175 @@ public class ZkDiscoveryServiceTest {
verify(partitionService, times(1)).recalculatePartitions(eq(currentInfo), eq(List.of(anotherInfo, childInfo)));
}
@Test
public void publishCurrentServerUpdatesExistingNodeTest() throws Exception {
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(SESSION_ID));
mockSessionId();
SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
when(client.setData()).thenReturn(setDataBuilder);
when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(currentInfo);
zkDiscoveryService.publishCurrentServer();
verify(setDataBuilder).forPath(currentData.getPath(), currentInfo.toByteArray());
verify(client, never()).create();
}
@Test
public void publishCurrentServerUpdatesNodeWithOutdatedDataTest() throws Exception {
TransportProtos.ServiceInfo updatedInfo = currentInfo.toBuilder().setReady(true).build();
when(serviceInfoProvider.getServiceInfo()).thenReturn(updatedInfo);
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(SESSION_ID));
mockSessionId();
SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
when(client.setData()).thenReturn(setDataBuilder);
when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(updatedInfo);
zkDiscoveryService.publishCurrentServer();
verify(setDataBuilder).forPath(currentData.getPath(), updatedInfo.toByteArray());
verify(client, never()).create();
}
@Test
public void publishCurrentServerCreatesNodeWhenAbsentTest() throws Exception {
String newPath = "/thingsboard/nodes/0000000011";
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(null);
CreateBuilder createBuilder = mock(CreateBuilder.class, RETURNS_DEEP_STUBS);
when(client.create()).thenReturn(createBuilder);
when(createBuilder.creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/thingsboard/nodes/node-", currentInfo.toByteArray()))
.thenReturn(newPath);
when(client.getConnectionStateListenable()).thenReturn(mock(Listenable.class));
zkDiscoveryService.publishCurrentServer();
assertEquals(newPath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
verify(client, never()).setData();
}
@Test
public void publishCurrentServerCreatesNodeWhenExistingNodeOwnedByAnotherSessionTest() throws Exception {
String newPath = "/thingsboard/nodes/0000000011";
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(OTHER_SESSION_ID));
mockSessionId();
CreateBuilder createBuilder = mock(CreateBuilder.class, RETURNS_DEEP_STUBS);
when(client.create()).thenReturn(createBuilder);
when(createBuilder.creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/thingsboard/nodes/node-", currentInfo.toByteArray()))
.thenReturn(newPath);
when(client.getConnectionStateListenable()).thenReturn(mock(Listenable.class));
zkDiscoveryService.publishCurrentServer();
assertEquals(newPath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
verify(client, never()).setData();
}
@Test
public void publishCurrentServerSkipsWhenNodeStateUnknownTest() throws Exception {
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenThrow(new InterruptedException());
zkDiscoveryService.publishCurrentServer();
assertTrue(Thread.interrupted());
assertEquals(currentData.getPath(), ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
verify(client, never()).create();
verify(client, never()).setData();
}
@Test
public void getOtherServersIgnoresNodesWithCurrentServiceIdTest() {
dataList.add(new ChildData("/thingsboard/nodes/0000000011", statWithCzxid(1), currentInfo.toByteArray()));
dataList.add(childData);
assertEquals(List.of(childInfo), zkDiscoveryService.getOtherServers());
}
@Test
public void getOtherServersKeepsLatestNodeForDuplicatedServiceIdTest() {
TransportProtos.ServiceInfo latestInfo = childInfo.toBuilder().setReady(true).build();
dataList.add(new ChildData("/thingsboard/nodes/0000000020", statWithCzxid(1), childInfo.toByteArray()));
dataList.add(new ChildData("/thingsboard/nodes/0000000021", statWithCzxid(2), latestInfo.toByteArray()));
assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers());
Collections.swap(dataList, 1, 2);
assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers());
}
@Test
public void getOtherServersKeepsLatestCreatedNodeEvenIfItsMtimeIsOlderTest() {
TransportProtos.ServiceInfo latestInfo = childInfo.toBuilder().setReady(true).build();
Stat staleStat = statWithCzxid(1);
staleStat.setMtime(2000);
Stat latestStat = statWithCzxid(2);
latestStat.setMtime(1000);
dataList.add(new ChildData("/thingsboard/nodes/0000000020", staleStat, childInfo.toByteArray()));
dataList.add(new ChildData("/thingsboard/nodes/0000000021", latestStat, latestInfo.toByteArray()));
assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers());
}
@Test
public void nodeWithCurrentServiceIdDoesNotTriggerRecalculationTest() {
ChildData orphanData = new ChildData("/thingsboard/nodes/0000000011", statWithCzxid(1), currentInfo.toByteArray());
startNode(orphanData);
stopNode(orphanData);
assertTrue(zkDiscoveryService.delayedTasks.isEmpty());
verify(partitionService, never()).recalculatePartitions(any(), any());
verify(applicationEventPublisher, never()).publishEvent(any(OtherServiceShutdownEvent.class));
}
@Test
public void removalOfDuplicatedNodeDoesNotPublishShutdownEventTest() {
ChildData staleData = new ChildData("/thingsboard/nodes/0000000019", statWithCzxid(1), childInfo.toByteArray());
ChildData liveData = new ChildData("/thingsboard/nodes/0000000020", statWithCzxid(2), childInfo.toByteArray());
startNode(staleData);
startNode(liveData);
stopNode(staleData);
assertTrue(zkDiscoveryService.delayedTasks.isEmpty());
verify(applicationEventPublisher, never()).publishEvent(any(OtherServiceShutdownEvent.class));
stopNode(liveData);
assertEquals(1, zkDiscoveryService.delayedTasks.size());
}
private ExistsBuilder mockExistsBuilder() {
ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
when(client.checkExists()).thenReturn(existsBuilder);
return existsBuilder;
}
private void mockSessionId() throws Exception {
CuratorZookeeperClient zookeeperClient = mock(CuratorZookeeperClient.class);
ZooKeeper zooKeeper = mock(ZooKeeper.class);
when(client.getZookeeperClient()).thenReturn(zookeeperClient);
when(zookeeperClient.getZooKeeper()).thenReturn(zooKeeper);
when(zooKeeper.getSessionId()).thenReturn(SESSION_ID);
}
private static Stat statOwnedBy(long sessionId) {
Stat stat = new Stat();
stat.setEphemeralOwner(sessionId);
return stat;
}
private static Stat statWithCzxid(long czxid) {
Stat stat = new Stat();
stat.setCzxid(czxid);
return stat;
}
private void startNode(ChildData data) {
dataList.add(data);
zkDiscoveryService.onCacheEvent(NODE_CREATED, null, data);

109
common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java

@ -0,0 +1,109 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.queue.discovery;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.gen.transport.TransportProtos;
import java.time.Duration;
import java.util.List;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
@ExtendWith(MockitoExtension.class)
public class ZkDiscoveryServiceZkTest {
private static final String ZK_NODES_DIR = "/thingsboard/nodes";
private static final String PROTECTED_NODE_NAME_REGEX = "_c_[0-9a-f-]{36}-node-\\d{10}";
@Mock
private ApplicationEventPublisher applicationEventPublisher;
@Mock
private TbServiceInfoProvider serviceInfoProvider;
@Mock
private PartitionService partitionService;
private final TransportProtos.ServiceInfo currentInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-core-0").build();
private TestingServer zkServer;
private CuratorFramework observer;
private ZkDiscoveryService zkDiscoveryService;
@BeforeEach
public void setup() throws Exception {
zkServer = new TestingServer(true);
observer = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), new RetryOneTime(100));
observer.start();
lenient().when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo);
lenient().when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(currentInfo);
zkDiscoveryService = new ZkDiscoveryService(applicationEventPublisher, serviceInfoProvider, partitionService);
ReflectionTestUtils.setField(zkDiscoveryService, "zkUrl", zkServer.getConnectString());
ReflectionTestUtils.setField(zkDiscoveryService, "zkRetryInterval", 100);
ReflectionTestUtils.setField(zkDiscoveryService, "zkConnectionTimeout", 3000);
ReflectionTestUtils.setField(zkDiscoveryService, "zkSessionTimeout", 3000);
ReflectionTestUtils.setField(zkDiscoveryService, "zkDir", "/thingsboard");
ReflectionTestUtils.setField(zkDiscoveryService, "recalculateDelay", 0L);
zkDiscoveryService.init();
zkDiscoveryService.onApplicationEvent(null);
}
@AfterEach
public void tearDown() throws Exception {
ReflectionTestUtils.invokeMethod(zkDiscoveryService, "destroy");
CloseableUtils.closeQuietly(observer);
zkServer.close();
}
@Test
public void publishCreatesSingleProtectedNodeAndExcludesItFromOtherServersTest() throws Exception {
List<String> nodes = observer.getChildren().forPath(ZK_NODES_DIR);
assertEquals(1, nodes.size());
assertTrue(nodes.get(0).matches(PROTECTED_NODE_NAME_REGEX), nodes.get(0));
assertEquals(ZK_NODES_DIR + "/" + nodes.get(0), ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertTrue(zkDiscoveryService.getOtherServers().isEmpty()));
}
@Test
public void sessionExpiryLeavesSingleNodeOwnedByCurrentSessionTest() throws Exception {
String nodeBeforeExpiry = observer.getChildren().forPath(ZK_NODES_DIR).get(0);
zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
await().atMost(Duration.ofSeconds(30))
.during(Duration.ofSeconds(2))
.ignoreExceptions()
.untilAsserted(() -> {
List<String> nodes = observer.getChildren().forPath(ZK_NODES_DIR);
assertEquals(1, nodes.size());
String nodePath = ZK_NODES_DIR + "/" + nodes.get(0);
assertNotEquals(nodeBeforeExpiry, nodes.get(0));
assertEquals(nodePath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
Stat stat = observer.checkExists().forPath(nodePath);
long sessionId = zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getSessionId();
assertEquals(sessionId, stat.getEphemeralOwner());
assertTrue(zkDiscoveryService.getOtherServers().isEmpty());
});
}
}

2
common/script/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/script/remote-js-client/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>script</artifactId>
</parent>
<groupId>org.thingsboard.common.script</groupId>

2
common/script/script-api/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>script</artifactId>
</parent>
<groupId>org.thingsboard.common.script</groupId>

26
common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java

@ -127,14 +127,22 @@ public class NashornJsInvokeService extends AbstractJsInvokeService {
@Override
protected ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) {
// A top-level function declaration creates a non-configurable property on the Nashorn Global
// that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap
// shape history forever. Declaring the function inside an IIFE and assigning it to a global
// property keeps the property configurable, allowing doRelease() to actually delete it.
// The prefix stays on the first line to preserve line numbering on the raw engine path;
// the sandbox beautifier reformats the wrapper and shifts reported error lines anyway.
String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript
+ "\nreturn " + scriptInfo.getFunctionName() + ";\n})();";
return jsExecutor.submit(() -> {
try {
evalLock.lock();
try {
if (useJsSandbox) {
sandbox.eval(jsScript);
sandbox.eval(wrappedScript);
} else {
engine.eval(jsScript);
engine.eval(wrappedScript);
}
} finally {
evalLock.unlock();
@ -169,10 +177,16 @@ public class NashornJsInvokeService extends AbstractJsInvokeService {
}
protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException {
if (useJsSandbox) {
sandbox.eval(scriptInfo.getFunctionName() + " = undefined;");
} else {
engine.eval(scriptInfo.getFunctionName() + " = undefined;");
String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];";
evalLock.lock();
try {
if (useJsSandbox) {
sandbox.eval(deleteScript);
} else {
engine.eval(deleteScript);
}
} finally {
evalLock.unlock();
}
}

109
common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java

@ -0,0 +1,109 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.script.api.js;
import delight.nashornsandbox.NashornSandbox;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.script.api.ScriptType;
import org.thingsboard.script.api.TbScriptException;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.stats.StatsFactory;
import javax.script.ScriptEngine;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
/**
* Covers the JS global scope lifecycle against both backends the service can be configured with.
* The Spring-wired {@code NashornJsInvokeServiceTest} only exercises the sandbox, since
* {@code js.local.use_js_sandbox} defaults to true.
*/
class NashornJsInvokeServiceLifecycleTest {
private static final String[] ARG_NAMES = {"msg", "metadata", "msgType"};
private NashornJsInvokeService service;
private boolean useJsSandbox;
@AfterEach
void tearDown() {
if (service != null) {
service.stop();
}
}
@ParameterizedTest(name = "useJsSandbox = {0}")
@ValueSource(booleans = {true, false})
void whenScriptIsReleased_thenGlobalPropertyIsRemovedAndFunctionIsGone(boolean useJsSandbox) throws Exception {
givenService(useJsSandbox);
UUID scriptId = UUID.randomUUID();
JsScriptInfo scriptInfo = eval(scriptId, "return {doubled: msg.temperature * 2};");
assertThat(hasGlobalProperty(scriptInfo)).isTrue();
assertThat(invoke(scriptId, scriptInfo, "{\"temperature\":21}")).asString().contains("\"doubled\":42");
service.doRelease(scriptId);
assertThat(hasGlobalProperty(scriptInfo)).isFalse();
assertThatThrownBy(() -> invoke(scriptId, scriptInfo, "{\"temperature\":21}"))
.isInstanceOf(ExecutionException.class)
.cause()
.isInstanceOf(TbScriptException.class);
}
@ParameterizedTest(name = "useJsSandbox = {0}")
@ValueSource(booleans = {true, false})
void whenOneOfTwoScriptsIsReleased_thenTheOtherKeepsWorking(boolean useJsSandbox) throws Exception {
givenService(useJsSandbox);
UUID releasedId = UUID.randomUUID();
UUID retainedId = UUID.randomUUID();
JsScriptInfo released = eval(releasedId, "return {v: 1};");
JsScriptInfo retained = eval(retainedId, "return {v: 2};");
service.doRelease(releasedId);
assertThat(hasGlobalProperty(released)).isFalse();
assertThat(hasGlobalProperty(retained)).isTrue();
assertThat(invoke(retainedId, retained, "{}")).asString().contains("\"v\":2");
}
private void givenService(boolean useJsSandbox) {
this.useJsSandbox = useJsSandbox;
service = new NashornJsInvokeService(Optional.empty(), Optional.empty());
ReflectionTestUtils.setField(service, "statsFactory", mock(StatsFactory.class, Mockito.RETURNS_DEEP_STUBS));
ReflectionTestUtils.setField(service, "useJsSandbox", useJsSandbox);
ReflectionTestUtils.setField(service, "jsExecutorThreadPoolSize", 4);
ReflectionTestUtils.setField(service, "monitorThreadPoolSize", 2);
ReflectionTestUtils.setField(service, "maxCpuTime", 8000L);
ReflectionTestUtils.setField(service, "maxMemory", 104857600L);
service.init();
}
private JsScriptInfo eval(UUID scriptId, String scriptBody) throws Exception {
service.doEvalScript(TenantId.SYS_TENANT_ID, ScriptType.RULE_NODE_SCRIPT, scriptBody, scriptId, ARG_NAMES).get();
return service.scriptInfoMap.get(scriptId);
}
private Object invoke(UUID scriptId, JsScriptInfo scriptInfo, String msg) throws Exception {
return service.doInvokeFunction(scriptId, scriptInfo, new Object[]{msg, "{}", "POST_TELEMETRY_REQUEST"}).get();
}
private boolean hasGlobalProperty(JsScriptInfo scriptInfo) throws Exception {
String expression = "this.hasOwnProperty('" + scriptInfo.getFunctionName() + "')";
Object result = useJsSandbox
? ((NashornSandbox) ReflectionTestUtils.getField(service, "sandbox")).eval(expression)
: ((ScriptEngine) ReflectionTestUtils.getField(service, "engine")).eval(expression);
return Boolean.TRUE.equals(result);
}
}

2
common/stats/pom.xml

@ -11,7 +11,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/transport/coap/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.common.transport</groupId>

2
common/transport/http/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.common.transport</groupId>

2
common/transport/lwm2m/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.common.transport</groupId>

2
common/transport/mqtt/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.common.transport</groupId>

2
common/transport/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

2
common/transport/snmp/pom.xml

@ -10,7 +10,7 @@
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>

2
common/transport/transport-api/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.common</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.common.transport</groupId>

2
common/util/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>

16
common/util/src/main/java/org/thingsboard/common/util/SetCache.java

@ -14,9 +14,19 @@ public class SetCache<K> {
private final Cache<K, Object> cache;
public SetCache(long valueTtlMs) {
this.cache = Caffeine.newBuilder()
.expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS)
.build();
this(Caffeine.newBuilder().expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS));
}
private SetCache(Caffeine<Object, Object> builder) {
this.cache = builder.build();
}
/**
* Bounded by entry count with LRU-ish eviction, instead of a TTL - for callers that want to remember
* up to N recently seen keys rather than expire entries after a fixed duration.
*/
public static <T> SetCache<T> boundedBySize(int maximumSize) {
return new SetCache<>(Caffeine.newBuilder().maximumSize(maximumSize));
}
public void add(K key) {

6
common/version-control/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>common</artifactId>
</parent>
<groupId>org.thingsboard.common</groupId>
@ -58,6 +58,10 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>

6
dao/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>thingsboard</artifactId>
</parent>
<artifactId>dao</artifactId>
@ -169,6 +169,10 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>

2
edqs/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>thingsboard</artifactId>
</parent>
<artifactId>edqs</artifactId>

2
monitoring/pom.xml

@ -10,7 +10,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>thingsboard</artifactId>
</parent>

2
msa/black-box-tests/pom.xml

@ -10,7 +10,7 @@
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>

2
msa/edqs/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>

2
msa/js-executor/docker/Dockerfile

@ -3,7 +3,7 @@
# SPDX-License-Identifier: Apache-2.0
#
FROM thingsboard/node:22.22.2-bookworm-slim
FROM thingsboard/node:22.23.4-bookworm-slim
ENV NODE_ENV production
ENV DOCKER_MODE true

7
msa/js-executor/package.json

@ -1,15 +1,15 @@
{
"name": "thingsboard-js-executor",
"private": true,
"version": "4.2.2.6",
"version": "4.2.2.7",
"description": "ThingsBoard JavaScript Executor Microservice",
"main": "server.ts",
"bin": "server.js",
"scripts": {
"pkg": "tsc && pkg -t node22-linux-x64 --output ./target/thingsboard-js-executor-linux ./target/src && pkg -t node22-win-x64 --no-bytecode --public-packages \"*\" --public --output ./target/thingsboard-js-executor-win.exe ./target/src && node install.js",
"test": "mkdir -p target/surefire-reports && node --require ts-node/register --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=target/surefire-reports/TEST-js-executor.xml test/jsExecutor.test.ts",
"start": "nodemon --watch '.' --ext 'ts' --exec 'ts-node server.ts'",
"start-prod": "nodemon --watch '.' --ext 'ts' --exec 'NODE_ENV=production ts-node server.ts'",
"start": "node --watch --watch-preserve-output -r ts-node/register server.ts",
"start-prod": "NODE_ENV=production node --watch --watch-preserve-output -r ts-node/register server.ts",
"build": "tsc"
},
"dependencies": {
@ -38,7 +38,6 @@
"@types/uuid-parse": "^1.0.2",
"@yao-pkg/pkg": "^6.6.0",
"fs-extra": "^11.3.1",
"nodemon": "^3.1.10",
"ts-node": "^10.9.2",
"typescript": "~5.9.3"
},

23
msa/js-executor/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>
@ -30,6 +30,13 @@
<pkg.package.phase>package</pkg.package.phase>
<pkg.linux.dist>${project.build.directory}/package/linux</pkg.linux.dist>
<pkg.win.dist>${project.build.directory}/package/windows</pkg.win.dist>
<!-- The `yarn test` execution has to be skipped when tests are skipped and also when the
yarn build as a whole is skipped: with `yarn install` skipped there is no node_modules
to run the tests from. Maven has no boolean OR, so skip.yarn is used as the default
here (honoured both from the command line and from a pom property) and the
skip-yarn-test profile below folds in maven.test.skip, which is only ever passed on
the command line. -->
<yarn.test.skip>${skip.yarn}</yarn.test.skip>
<docker.push-arm-amd-image.phase>pre-integration-test</docker.push-arm-amd-image.phase>
</properties>
@ -112,7 +119,7 @@
</goals>
<phase>test</phase>
<configuration>
<skip>${maven.test.skip}</skip>
<skip>${yarn.test.skip}</skip>
<arguments>--mutex network run test</arguments>
</configuration>
</execution>
@ -206,6 +213,18 @@
</plugins>
</build>
<profiles>
<profile>
<id>skip-yarn-test</id>
<activation>
<property>
<name>maven.test.skip</name>
<value>true</value>
</property>
</activation>
<properties>
<yarn.test.skip>true</yarn.test.skip>
</properties>
</profile>
<profile>
<id>yarn-start</id>
<activation>

231
msa/js-executor/yarn.lock

@ -379,14 +379,6 @@ ansi-styles@^4.0.0:
dependencies:
color-convert "^2.0.1"
anymatch@~3.1.2:
version "3.1.3"
resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e"
integrity sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==
dependencies:
normalize-path "^3.0.0"
picomatch "^2.0.4"
arg@^4.1.0:
version "4.1.3"
resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089"
@ -402,21 +394,11 @@ async@^3.2.3:
resolved "https://registry.yarnpkg.com/async/-/async-3.2.6.tgz#1b0728e14929d51b85b449b7f06e27c1145e38ce"
integrity sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==
balanced-match@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
base64-js@^1.3.1:
version "1.5.1"
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a"
integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==
binary-extensions@^2.0.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.3.0.tgz#f6e14a97858d327252200242d4ccfe522c445522"
integrity sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==
bl@^4.0.3:
version "4.1.0"
resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a"
@ -446,21 +428,6 @@ body-parser@^2.2.0:
raw-body "^3.0.0"
type-is "^2.0.0"
brace-expansion@^1.1.7:
version "1.1.18"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.18.tgz#3ce74d89885136be1535341f8c3d4425c29a5cab"
integrity sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==
dependencies:
balanced-match "^1.0.0"
concat-map "0.0.1"
braces@~3.0.2:
version "3.0.3"
resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789"
integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==
dependencies:
fill-range "^7.1.1"
buffer@^5.5.0:
version "5.7.1"
resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0"
@ -490,21 +457,6 @@ call-bound@^1.0.2:
call-bind-apply-helpers "^1.0.2"
get-intrinsic "^1.3.0"
chokidar@^3.5.2:
version "3.6.0"
resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.6.0.tgz#197c6cc669ef2a8dc5e7b4d97ee4e092c3eb0d5b"
integrity sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==
dependencies:
anymatch "~3.1.2"
braces "~3.0.2"
glob-parent "~5.1.2"
is-binary-path "~2.1.0"
is-glob "~4.0.1"
normalize-path "~3.0.0"
readdirp "~3.6.0"
optionalDependencies:
fsevents "~2.3.2"
chownr@^1.1.1:
version "1.1.4"
resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b"
@ -572,11 +524,6 @@ colorspace@1.1.x:
color "^3.1.3"
text-hex "1.0.x"
concat-map@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==
config@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/config/-/config-4.1.1.tgz#798f636e2a5b7baa7050280d1eb21f8e10abb8c9"
@ -616,7 +563,7 @@ create-require@^1.1.0:
resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333"
integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==
debug@4, debug@^4, debug@^4.3.5, debug@^4.4.0:
debug@4, debug@^4.3.5, debug@^4.4.0:
version "4.4.1"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.1.tgz#e5a8bc6cbc4c6cd3e64308b0693a3d4fa550189b"
integrity sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==
@ -780,13 +727,6 @@ file-stream-rotator@^0.6.1:
dependencies:
moment "^2.29.1"
fill-range@^7.1.1:
version "7.1.1"
resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292"
integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==
dependencies:
to-regex-range "^5.0.1"
finalhandler@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-2.1.0.tgz#72306373aa89d05a8242ed569ed86a1bff7c561f"
@ -836,11 +776,6 @@ fs-extra@^11.2.0, fs-extra@^11.3.1:
jsonfile "^6.0.1"
universalify "^2.0.0"
fsevents@~2.3.2:
version "2.3.3"
resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6"
integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==
function-bind@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c"
@ -880,13 +815,6 @@ github-from-package@0.0.0:
resolved "https://registry.yarnpkg.com/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce"
integrity sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==
glob-parent@~5.1.2:
version "5.1.2"
resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4"
integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==
dependencies:
is-glob "^4.0.1"
gopd@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1"
@ -897,11 +825,6 @@ graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.2:
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3"
integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
integrity sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==
has-symbols@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338"
@ -945,11 +868,6 @@ ieee754@^1.1.13:
resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352"
integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==
ignore-by-default@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/ignore-by-default/-/ignore-by-default-1.0.1.tgz#48ca6d72f6c6a3af00a9ad4ae6876be3889e2b09"
integrity sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==
inherits@2.0.4, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3:
version "2.0.4"
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"
@ -978,13 +896,6 @@ is-arrayish@^0.3.1:
resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.3.2.tgz#4574a2ae56f7ab206896fb431eaeed066fdf8f03"
integrity sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==
is-binary-path@~2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09"
integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==
dependencies:
binary-extensions "^2.0.0"
is-core-module@^2.16.0:
version "2.16.1"
resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.16.1.tgz#2a98801a849f43e2add644fbb6bc6229b19a4ef4"
@ -992,28 +903,11 @@ is-core-module@^2.16.0:
dependencies:
hasown "^2.0.2"
is-extglob@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2"
integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==
is-fullwidth-code-point@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
is-glob@^4.0.1, is-glob@~4.0.1:
version "4.0.3"
resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084"
integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==
dependencies:
is-extglob "^2.1.1"
is-number@^7.0.0:
version "7.0.0"
resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b"
integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==
is-promise@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-4.0.0.tgz#42ff9f84206c1991d26debf520dd5c01042dd2f3"
@ -1140,13 +1034,6 @@ mimic-response@^3.1.0:
resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9"
integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==
minimatch@^3.1.2:
version "3.1.5"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.5.tgz#580c88f8d5445f2bd6aa8f3cadefa0de79fbd69e"
integrity sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==
dependencies:
brace-expansion "^1.1.7"
minimist@^1.2.0, minimist@^1.2.3, minimist@^1.2.6:
version "1.2.8"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c"
@ -1170,9 +1057,9 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3:
integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==
moment@^2.29.1:
version "2.30.1"
resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae"
integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==
version "2.31.0"
resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa"
integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw==
ms@^2.1.1, ms@^2.1.3:
version "2.1.3"
@ -1216,33 +1103,12 @@ node-int64@^0.4.0:
resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"
integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==
nodemon@^3.1.10:
version "3.1.10"
resolved "https://registry.yarnpkg.com/nodemon/-/nodemon-3.1.10.tgz#5015c5eb4fffcb24d98cf9454df14f4fecec9bc1"
integrity sha512-WDjw3pJ0/0jMFmyNDp3gvY2YizjLmmOUQo6DEBY+JgdvW/yQ9mEeSw6H5ythl5Ny2ytb7f9C2nIbjSxMNzbJXw==
dependencies:
chokidar "^3.5.2"
debug "^4"
ignore-by-default "^1.0.1"
minimatch "^3.1.2"
pstree.remy "^1.1.8"
semver "^7.5.3"
simple-update-notifier "^2.0.0"
supports-color "^5.5.0"
touch "^3.1.0"
undefsafe "^2.0.5"
normalize-path@^3.0.0, normalize-path@~3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65"
integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==
object-hash@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-3.0.0.tgz#73f97f753e7baffc0e2cc9d6e079079744ac82e9"
integrity sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==
object-inspect@^1.13.3:
object-inspect@^1.13.3, object-inspect@^1.13.4:
version "1.13.4"
resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.4.tgz#8375265e21bc20d0fa582c22e1b13485d6e00213"
integrity sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==
@ -1293,11 +1159,6 @@ picocolors@^1.1.0:
resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b"
integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==
picomatch@^2.0.4, picomatch@^2.2.1:
version "2.3.2"
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.2.tgz#5a942915e26b372dc0f0e6753149a16e6b1c5601"
integrity sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==
picomatch@^4.0.2:
version "4.0.4"
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.4.tgz#fd6f5e00a143086e074dffe4c924b8fb293b0589"
@ -1332,18 +1193,13 @@ progress@^2.0.3:
integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==
proxy-addr@^2.0.7:
version "2.0.7"
resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025"
integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==
version "2.0.8"
resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932"
integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==
dependencies:
forwarded "0.2.0"
ipaddr.js "1.9.1"
pstree.remy@^1.1.8:
version "1.1.8"
resolved "https://registry.yarnpkg.com/pstree.remy/-/pstree.remy-1.1.8.tgz#c242224f4a67c21f686839bbdb4ac282b8373d3a"
integrity sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==
pump@^3.0.0:
version "3.0.3"
resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.3.tgz#151d979f1a29668dc0025ec589a455b53282268d"
@ -1353,11 +1209,12 @@ pump@^3.0.0:
once "^1.3.1"
qs@^6.14.0:
version "6.14.2"
resolved "https://registry.yarnpkg.com/qs/-/qs-6.14.2.tgz#b5634cf9d9ad9898e31fba3504e866e8efb6798c"
integrity sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==
version "6.16.1"
resolved "https://registry.yarnpkg.com/qs/-/qs-6.16.1.tgz#0643e17993e551759c85078e1f0bc4b9fe908020"
integrity sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==
dependencies:
side-channel "^1.1.0"
es-define-property "^1.0.1"
side-channel "^1.1.1"
range-parser@^1.2.1:
version "1.2.1"
@ -1406,13 +1263,6 @@ readable-stream@^3.1.1, readable-stream@^3.4.0, readable-stream@^3.6.0, readable
string_decoder "^1.1.1"
util-deprecate "^1.0.1"
readdirp@~3.6.0:
version "3.6.0"
resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7"
integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==
dependencies:
picomatch "^2.2.1"
require-directory@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"
@ -1458,7 +1308,7 @@ safe-stable-stringify@^2.3.1:
resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a"
integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==
semver@^7.3.5, semver@^7.5.3:
semver@^7.3.5:
version "7.7.2"
resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.2.tgz#67d99fdcd35cec21e6f8b87a7fd515a33f982b58"
integrity sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==
@ -1495,13 +1345,13 @@ setprototypeof@1.2.0:
resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424"
integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==
side-channel-list@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.0.tgz#10cb5984263115d3b7a0e336591e290a830af8ad"
integrity sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==
side-channel-list@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.1.tgz#c2e0b5a14a540aebee3bbc6c3f8666cc9b509127"
integrity sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==
dependencies:
es-errors "^1.3.0"
object-inspect "^1.13.3"
object-inspect "^1.13.4"
side-channel-map@^1.0.1:
version "1.0.1"
@ -1524,14 +1374,14 @@ side-channel-weakmap@^1.0.2:
object-inspect "^1.13.3"
side-channel-map "^1.0.1"
side-channel@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.0.tgz#c3fcff9c4da932784873335ec9765fa94ff66bc9"
integrity sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==
side-channel@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.1.tgz#ea02c62e05dc4bea67d4442f0fb71ee192f8e0ab"
integrity sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==
dependencies:
es-errors "^1.3.0"
object-inspect "^1.13.3"
side-channel-list "^1.0.0"
object-inspect "^1.13.4"
side-channel-list "^1.0.1"
side-channel-map "^1.0.1"
side-channel-weakmap "^1.0.2"
@ -1556,13 +1406,6 @@ simple-swizzle@^0.2.2:
dependencies:
is-arrayish "^0.3.1"
simple-update-notifier@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz#d70b92bdab7d6d90dfd73931195a30b6e3d7cebb"
integrity sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==
dependencies:
semver "^7.5.3"
stack-trace@0.0.x:
version "0.0.10"
resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0"
@ -1620,13 +1463,6 @@ strip-json-comments@~2.0.1:
resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a"
integrity sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==
supports-color@^5.5.0:
version "5.5.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f"
integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==
dependencies:
has-flag "^3.0.0"
supports-preserve-symlinks-flag@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09"
@ -1677,23 +1513,11 @@ tinyglobby@^0.2.11:
fdir "^6.4.4"
picomatch "^4.0.2"
to-regex-range@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4"
integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==
dependencies:
is-number "^7.0.0"
toidentifier@1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35"
integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==
touch@^3.1.0:
version "3.1.1"
resolved "https://registry.yarnpkg.com/touch/-/touch-3.1.1.tgz#097a23d7b161476435e5c1344a95c0f75b4a5694"
integrity sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==
tr46@~0.0.3:
version "0.0.3"
resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a"
@ -1744,11 +1568,6 @@ typescript@~5.9.3:
resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.9.3.tgz#5b4f59e15310ab17a216f5d6cf53ee476ede670f"
integrity sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==
undefsafe@^2.0.5:
version "2.0.5"
resolved "https://registry.yarnpkg.com/undefsafe/-/undefsafe-2.0.5.tgz#38733b9327bdcd226db889fb723a6efd162e6e2c"
integrity sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==
undici-types@~6.21.0:
version "6.21.0"
resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.21.0.tgz#691d00af3909be93a7faa13be61b3a5b50ef12cb"

2
msa/monitoring/pom.xml

@ -11,7 +11,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>

38
msa/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>thingsboard</artifactId>
</parent>
<artifactId>msa</artifactId>
@ -55,10 +55,7 @@
</modules>
<profiles>
<!-- Mirror of the root-pom skip-deb profile. Required because Maven resolves
child <properties> entries (pkg.deb.phase=package above) with higher priority
than profile properties from a parent POM. Redeclaring the profile here ensures
pkg.deb.phase=none wins when -Dpkg.skip.deb=true is passed. -->
<!-- Activated by -Dpkg.skip.deb=true. Skips the .deb enforce/copy executions. -->
<profile>
<id>skip-deb</id>
<activation>
@ -71,9 +68,9 @@
<pkg.deb.phase>none</pkg.deb.phase>
</properties>
</profile>
<!-- Mirror of the root-pom skip-pkg profile. Same precedence reason as skip-deb above:
pkg.deb.phase=package in this POM's <properties> would win over the parent profile,
so we must redeclare it here to ensure pkg.deb.phase=none when -Dpkg.skip=true. -->
<!-- Activated by -Dpkg.skip=true. Needed alongside skip-deb because profile activation
only sees CLI/system properties, so pkg.skip.deb=true set by the root skip-pkg
profile does not activate skip-deb. -->
<profile>
<id>skip-pkg</id>
<activation>
@ -86,6 +83,31 @@
<pkg.deb.phase>none</pkg.deb.phase>
</properties>
</profile>
<!-- Mirror the root skip-pkg-without-* profiles: no .deb is built when the UI build is skipped. -->
<profile>
<id>skip-pkg-without-yarn</id>
<activation>
<property>
<name>skip.yarn</name>
<value>true</value>
</property>
</activation>
<properties>
<pkg.deb.phase>none</pkg.deb.phase>
</properties>
</profile>
<profile>
<id>skip-pkg-without-ui-build</id>
<activation>
<property>
<name>skip.ui.build</name>
<value>true</value>
</property>
</activation>
<properties>
<pkg.deb.phase>none</pkg.deb.phase>
</properties>
</profile>
<profile>
<id>black-box-tests</id>
<activation>

2
msa/tb-node/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>

2
msa/tb/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>

2
msa/transport/coap/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.msa</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.msa.transport</groupId>

2
msa/transport/http/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.msa</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.msa.transport</groupId>

2
msa/transport/lwm2m/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.msa</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.msa.transport</groupId>

2
msa/transport/mqtt/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard.msa</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>transport</artifactId>
</parent>
<groupId>org.thingsboard.msa.transport</groupId>

2
msa/transport/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>

2
msa/transport/snmp/pom.xml

@ -10,7 +10,7 @@
<parent>
<groupId>org.thingsboard.msa</groupId>
<artifactId>transport</artifactId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
</parent>
<groupId>org.thingsboard.msa.transport</groupId>

2
msa/vc-executor-docker/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>

2
msa/vc-executor/pom.xml

@ -10,7 +10,7 @@
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>

2
msa/web-ui/docker/Dockerfile

@ -3,7 +3,7 @@
# SPDX-License-Identifier: Apache-2.0
#
FROM thingsboard/node:22.22.2-bookworm-slim
FROM thingsboard/node:22.23.4-bookworm-slim
ENV NODE_ENV production
ENV DOCKER_MODE true

9
msa/web-ui/package.json

@ -1,19 +1,19 @@
{
"name": "thingsboard-web-ui",
"private": true,
"version": "4.2.2.6",
"version": "4.2.2.7",
"description": "ThingsBoard Web UI Microservice",
"main": "server.ts",
"bin": "server.js",
"scripts": {
"pkg": "tsc && pkg -t node22-linux-x64 --output ./target/thingsboard-web-ui-linux ./target/src && pkg -t node22-win-x64 --no-bytecode --public-packages \"*\" --public --output ./target/thingsboard-web-ui-win.exe ./target/src && node install.js",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --watch '.' --ext 'ts' --exec 'WEB_FOLDER=./target/web ts-node server.ts'",
"start-prod": "nodemon --watch '.' --ext 'ts' --exec 'WEB_FOLDER=./target/web NODE_ENV=production ts-node server.ts'",
"start": "WEB_FOLDER=./target/web node --watch --watch-preserve-output -r ts-node/register server.ts",
"start-prod": "WEB_FOLDER=./target/web NODE_ENV=production node --watch --watch-preserve-output -r ts-node/register server.ts",
"build": "tsc"
},
"dependencies": {
"compression": "^1.8.1",
"compression": "^1.8.2",
"config": "^3.3.12",
"connect-history-api-fallback": "1.6.0",
"express": "^5.1.0",
@ -40,7 +40,6 @@
"@types/node": "~22.17.2",
"@yao-pkg/pkg": "^6.6.0",
"fs-extra": "^11.3.1",
"nodemon": "^3.1.10",
"ts-node": "^10.9.2",
"typescript": "~5.9.3"
},

5
msa/web-ui/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.2.2.6-SNAPSHOT</version>
<version>4.2.2.7-SNAPSHOT</version>
<artifactId>msa</artifactId>
</parent>
<groupId>org.thingsboard.msa</groupId>
@ -60,6 +60,9 @@
<configuration>
<installDirectory>target</installDirectory>
<workingDirectory>${basedir}</workingDirectory>
<!-- Declared at plugin level so that it covers every execution of this plugin,
including the ones contributed by the profiles below. -->
<skip>${skip.ui.build}</skip>
</configuration>
<executions>
<execution>

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save