diff --git a/TEST_FAST.md b/TEST_FAST.md
index fbea72db9c..11f8969fca 100644
--- a/TEST_FAST.md
+++ b/TEST_FAST.md
@@ -42,10 +42,12 @@ Use `-Dpkg.skip=true` to skip all packaging at once (equivalent to all four flag
|----------------------------|-------------------------------------------|--------------------------------------------------------------|
| `-Dpkg.skip=true` | All of the below (bootjar + deb + rpm + zip) | Yes |
| `-Dpkg.skip.bootjar=true` | `spring-boot:repackage` (`*-boot.jar`) | Yes — tests use the regular `.jar`, not the fat boot jar |
-| `-Dpkg.skip.deb=true` | Gradle `buildDeb` + Maven `attach-artifact` | Yes — MSA docker modules copy the DEB from `target/` directly |
+| `-Dpkg.skip.deb=true` | Gradle `buildDeb` | Yes — MSA docker modules copy the DEB from `target/` directly |
| `-Dpkg.skip.rpm=true` | Gradle `buildRpm` | Yes — no test depends on the RPM |
| `-Dpkg.skip.zip=true` | `maven-assembly-plugin` Windows ZIP | Yes — no test depends on the ZIP |
+`-Dskip.yarn=true` and `-Dskip.ui.build=true` imply `-Dpkg.skip=true`: packages built without the UI are incomplete.
+
## Testcontainers compatibility with the Docker API workaround
In case your tests failed to run testcontainers due to unsupported Docker API version
diff --git a/application/pom.xml b/application/pom.xml
index b6a59dba10..60a83d1873 100644
--- a/application/pom.xml
+++ b/application/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTthingsboardapplication
diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
index 4ac0a40442..fefec61c22 100644
--- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
+++ b/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()
diff --git a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java
index a7e3ed4ba9..2e8dda4d32 100644
--- a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java
+++ b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java
@@ -19,6 +19,7 @@ import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
+import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
@@ -34,6 +35,7 @@ import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.limit.LimitedApi;
+import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration;
import org.thingsboard.server.config.WebSocketConfiguration;
import org.thingsboard.server.dao.tenant.TbTenantProfileCache;
@@ -55,6 +57,7 @@ import org.thingsboard.server.service.ws.telemetry.cmd.TelemetryCmdsWrapper;
import java.io.IOException;
import java.security.InvalidParameterException;
+import java.util.EnumSet;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
@@ -76,6 +79,8 @@ import static org.thingsboard.server.service.ws.DefaultWebSocketService.NUMBER_O
@RequiredArgsConstructor
public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocketMsgEndpoint {
+ private static final Set USER_AUTHORITIES = EnumSet.of(Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER);
+
private final ConcurrentMap internalSessionMap = new ConcurrentHashMap<>();
private final ConcurrentMap externalSessionMap = new ConcurrentHashMap<>();
@@ -181,7 +186,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke
log.trace("{} Authenticating session", sessionRef);
SecurityUser securityCtx;
try {
- securityCtx = authenticationProvider.authenticate(authCmd.getToken());
+ securityCtx = authenticate(authCmd.getToken());
} catch (Exception e) {
close(sessionRef, CloseStatus.BAD_DATA.withReason(e.getMessage()));
return;
@@ -317,7 +322,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke
SecurityUser securityCtx = null;
String token = StringUtils.substringAfter(session.getUri().getQuery(), "token=");
if (StringUtils.isNotEmpty(token)) {
- securityCtx = authenticationProvider.authenticate(token);
+ securityCtx = authenticate(token);
}
return WebSocketSessionRef.builder()
.sessionId(UUID.randomUUID().toString())
@@ -328,6 +333,14 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke
.build();
}
+ private SecurityUser authenticate(String token) {
+ SecurityUser securityUser = authenticationProvider.authenticate(token);
+ if (!USER_AUTHORITIES.contains(securityUser.getAuthority())) {
+ throw new BadCredentialsException("Token is invalid");
+ }
+ return securityUser;
+ }
+
private SessionMetaData getSessionMd(String internalSessionId) {
SessionMetaData sessionMd = internalSessionMap.get(internalSessionId);
if (sessionMd == null) {
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
index 58b4cf719d..f6ad4143cf 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
@@ -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;
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
index 3f28a97955..702e43ac3d 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
@@ -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;
}
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
index 440c4f4106..8e46ae36e6 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
@@ -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 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.
+ *
+ * Only cheap non-blocking work may run inside the remapping function: it holds the bin lock of
+ * {@link #sessions} for this edge, so everything slow or lock-taking - {@link #destroySession},
+ * {@code EdgeGrpcSession.cleanUp()}, {@code save(...)}, {@code pushRuleEngineMessage(...)} or
+ * acquiring the per-edge new events lock - has to be done by the caller once compute has returned.
+ */
+ private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) {
+ AtomicReference replaced = new AtomicReference<>();
+ sessions.compute(edgeId, (id, current) -> {
+ replaced.set(current);
+ cancelScheduleEdgeEventsCheck(edgeId);
+ return session;
+ });
+ return replaced.get();
+ }
+
+ private 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.
+ *
+ * The remapping function is subject to the same "cheap non-blocking work only" rule as
+ * {@link #attachSession(EdgeId, EdgeGrpcSession)}.
+ */
+ private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) {
+ AtomicReference detached = new AtomicReference<>();
+ sessions.compute(edgeId, (id, current) -> {
+ if (current == null || !shouldDetach.test(current)) {
+ return current;
+ }
+ detached.set(current);
+ cancelScheduleEdgeEventsCheck(edgeId);
+ return null;
+ });
+ return detached.get();
+ }
+
+ /**
+ * 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 -> {
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
index dbb09ada8d..7ad1125533 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
@@ -9,6 +9,7 @@ import com.google.common.util.concurrent.SettableFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.databind.JsonNode;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.Device;
@@ -24,7 +25,10 @@ import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.msg.TbMsgType;
+import org.thingsboard.server.common.data.id.RpcId;
+import org.thingsboard.server.common.data.rpc.Rpc;
import org.thingsboard.server.common.data.rpc.RpcError;
+import org.thingsboard.server.common.data.rpc.RpcStatus;
import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgDataType;
@@ -125,7 +129,10 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
@Override
public ListenableFuture processDeviceRpcCallFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) {
log.trace("[{}] processDeviceRpcCallFromEdge [{}]", tenantId, deviceRpcCallMsg);
- if (deviceRpcCallMsg.hasResponseMsg()) {
+ if (deviceRpcCallMsg.hasRpcStatus()) {
+ // RPC v2 (persistent) status update from the edge - update the cloud Rpc entity (same id == request UUID).
+ return processDeviceRpcStatusFromEdge(tenantId, edge, deviceRpcCallMsg);
+ } else if (deviceRpcCallMsg.hasResponseMsg()) {
return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg);
} else if (deviceRpcCallMsg.hasRequestMsg()) {
return processDeviceRpcRequestFromEdge(tenantId, edge, deviceRpcCallMsg);
@@ -133,6 +140,46 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
return Futures.immediateFuture(null);
}
+ private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) {
+ RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB()));
+ Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId);
+ if (existingRpc == null) {
+ // RPC is unknown to the cloud (edge-originated or already deleted) - nothing to sync
+ log.debug("[{}][{}] Ignoring RPC status [{}] from edge - RPC not found", tenantId, rpcId, deviceRpcCallMsg.getRpcStatus());
+ return Futures.immediateFuture(null);
+ }
+ if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) {
+ // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy.
+ // Mark the edge-sync context so TbRpcService.deleteRpc does not echo the delete back to edges.
+ try {
+ edgeSynchronizationManager.getEdgeId().set(edge.getId());
+ edgeCtx.getTbRpcService().deleteRpc(tenantId, existingRpc);
+ } finally {
+ edgeSynchronizationManager.getEdgeId().remove();
+ }
+ return Futures.immediateFuture(null);
+ }
+ RpcStatus rpcStatus = RpcStatus.valueOf(deviceRpcCallMsg.getRpcStatus());
+ if (!existingRpc.getStatus().isIntermediate() && existingRpc.getStatus() != RpcStatus.TIMEOUT && rpcStatus.isIntermediate()) {
+ // guard against a final RPC regressing to an intermediate status (e.g. stale DELIVERED after SUCCESSFUL).
+ // TIMEOUT is not final - the device actor retries the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED).
+ log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already final [{}]",
+ tenantId, rpcId, rpcStatus, existingRpc.getStatus());
+ return Futures.immediateFuture(null);
+ }
+ JsonNode response = null;
+ if (deviceRpcCallMsg.hasResponseMsg() && !StringUtils.isEmpty(deviceRpcCallMsg.getResponseMsg().getResponse())) {
+ String payload = deviceRpcCallMsg.getResponseMsg().getResponse();
+ try {
+ response = JacksonUtil.toJsonNode(payload);
+ } catch (IllegalArgumentException e) {
+ response = JacksonUtil.newObjectNode().put("error", payload);
+ }
+ }
+ edgeCtx.getTbRpcService().save(tenantId, rpcId, rpcStatus, response);
+ return Futures.immediateFuture(null);
+ }
+
private ListenableFuture processDeviceRpcResponseFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) {
SettableFuture futureToSet = SettableFuture.create();
UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB());
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
index 767bad7dc7..7e6a2d88ad 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
@@ -7,9 +7,9 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
+import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.asset.AssetProfile;
-import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.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;
diff --git a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
index 3183277bd3..bc1c257d34 100644
--- a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
+++ b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
@@ -7,9 +7,11 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
+import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.common.util.SetCache;
import org.thingsboard.server.cache.TbTransactionalCache;
import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.data.ApiUsageState;
@@ -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 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 .}) are auto-created by the producer on
+ * first send. A {@code serviceId} that is not a member of the cluster - e.g. a stale node id or a value injected
+ * via message metadata - would therefore create an orphan topic that nobody ever consumes and that is never
+ * cleaned up. To prevent that, notifications whose target service id is not a current member of the cluster are
+ * skipped.
+ *
+ * This is a safety net for never-real ids, not a precise gatekeeper, so it is deliberately lenient. A service id is
+ * treated as known if it is either a current member ({@link PartitionService#isKnownServiceId}) or a recently seen
+ * one ({@link #recentlySeenServices}). The recently-seen grace covers nodes that are briefly absent from the live
+ * snapshot - a discovery-propagation lag, a rolling restart or a transient scale-down - so legitimate replies to
+ * them are not dropped; genuine non-delivery to a node that is actually gone is already handled by the caller-side
+ * RPC/REST timeout. The check also fails open while the cluster topology is not yet known (empty/absent membership,
+ * e.g. right after startup).
+ */
+ private boolean isUnknownService(ServiceType serviceType, String serviceId) {
+ if (serviceId == null || serviceId.isEmpty()) {
+ return true;
+ }
+ if (partitionService.isKnownServiceId(serviceType, serviceId)) {
+ return false; // currently a live member
+ }
+ Set serviceIds = partitionService.getAllServiceIds(serviceType);
+ if (serviceIds == null || serviceIds.isEmpty()) {
+ return false; // topology not known yet - fail open
+ }
+ return !recentlySeenServices.contains(recentlySeenServiceKey(serviceType, serviceId));
+ }
+
+ private void skipNotificationToUnknownService(ServiceType serviceType, String serviceId, TbQueueCallback callback) {
+ log.debug("Skipping notification push to unknown {} service id [{}]", serviceType, serviceId);
+ skippedUnknownServiceNfs.incrementAndGet();
+ if (callback != null) {
+ // Deliberate skip - the target is not a cluster member. Complete the callback as a no-op success,
+ // matching pushNotificationToTransport, so callers don't treat an intentional skip as a delivery error.
+ callback.onSuccess(null);
+ }
+ }
+
+ /**
+ * Records every observed cluster member so that {@link #isUnknownService} can grace a service id that has dropped
+ * out of the live snapshot (propagation lag, rolling restart, transient scale-down) instead of dropping
+ * notifications to it. Bounded by {@link #RECENTLY_SEEN_SERVICES_MAX_SIZE} with LRU eviction, so an id that is gone
+ * for good eventually ages out and the guard tightens again. Discovery events are change-only, so this never
+ * removes entries - it only adds; the live-snapshot check in {@link #isUnknownService} stays authoritative for
+ * current members.
+ */
+ @EventListener
+ public void onServiceListChanged(ServiceListChangedEvent event) {
+ rememberSeenService(event.getCurrentService());
+ List otherServices = event.getOtherServices();
+ if (otherServices != null) {
+ otherServices.forEach(this::rememberSeenService);
+ }
+ }
+
+ private void rememberSeenService(TransportProtos.ServiceInfo serviceInfo) {
+ if (serviceInfo == null) {
+ return;
+ }
+ String serviceId = serviceInfo.getServiceId();
+ if (serviceId == null || serviceId.isEmpty()) {
+ return;
+ }
+ for (String serviceType : serviceInfo.getServiceTypesList()) {
+ recentlySeenServices.add(recentlySeenServiceKey(serviceType, serviceId));
+ }
+ }
+
+ private static String recentlySeenServiceKey(ServiceType serviceType, String serviceId) {
+ return recentlySeenServiceKey(serviceType.name(), serviceId);
+ }
+
+ private static String recentlySeenServiceKey(String serviceType, String serviceId) {
+ return serviceType + ":" + serviceId;
+ }
+
@Override
public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) {
log.trace("PUSHING msg: {} to:{}", msg, tpi);
@@ -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);
}
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
index 5e1ea8e44e..b0a6a490ee 100644
--- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
+++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
@@ -3,12 +3,18 @@
package org.thingsboard.server.service.rpc;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.cluster.TbClusterService;
+import org.thingsboard.server.common.data.EdgeUtils;
+import org.thingsboard.server.common.data.edge.EdgeEvent;
+import org.thingsboard.server.common.data.edge.EdgeEventActionType;
+import org.thingsboard.server.common.data.edge.EdgeEventType;
import org.thingsboard.server.common.data.id.DeviceId;
+import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.RpcId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.msg.TbMsgType;
@@ -18,9 +24,14 @@ import org.thingsboard.server.common.data.rpc.Rpc;
import org.thingsboard.server.common.data.rpc.RpcStatus;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
+import org.thingsboard.server.dao.edge.EdgeEventService;
+import org.thingsboard.server.dao.edge.EdgeService;
+import org.thingsboard.server.dao.edge.EdgeSynchronizationManager;
import org.thingsboard.server.dao.rpc.RpcService;
import org.thingsboard.server.queue.util.TbCoreComponent;
+import java.util.List;
+
@TbCoreComponent
@Service
@RequiredArgsConstructor
@@ -28,6 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
public class TbRpcService {
private final RpcService rpcService;
private final TbClusterService tbClusterService;
+ private final EdgeService edgeService;
+ private final EdgeEventService edgeEventService;
+ private final EdgeSynchronizationManager edgeSynchronizationManager;
public Rpc save(TenantId tenantId, Rpc rpc) {
Rpc saved = rpcService.save(rpc);
@@ -67,4 +81,32 @@ public class TbRpcService {
return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
}
+ /**
+ * The only edge-aware RPC delete: propagates the delete to related edges (Cloud -> Edge) for ANY status.
+ * Other delete paths (RpcService.deleteRpc, TTL clean-up) intentionally do not sync, so each side expires its own copies.
+ */
+ public void deleteRpc(TenantId tenantId, Rpc rpc) {
+ rpcService.deleteRpc(tenantId, rpc.getId());
+ // skipped when the delete originated from an edge (edge-sync context) so it is not echoed back
+ if (edgeSynchronizationManager.getEdgeId().get() == null) {
+ pushRpcDeleteToEdges(tenantId, rpc);
+ }
+ }
+
+ private void pushRpcDeleteToEdges(TenantId tenantId, Rpc rpc) {
+ List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(tenantId, rpc.getDeviceId());
+ if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) {
+ return;
+ }
+ ObjectNode body = JacksonUtil.newObjectNode();
+ body.put("requestUUID", rpc.getId().getId().toString());
+ body.put("rpcStatus", RpcStatus.DELETED.name());
+ for (EdgeId edgeId : relatedEdgeIds) {
+ // persisted (not high-priority) so the delete is replayed when the edge reconnects
+ EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, EdgeEventType.DEVICE,
+ EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body);
+ edgeEventService.saveAsync(edgeEvent);
+ }
+ }
+
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
index 3668bef2ef..bf712a851b 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
@@ -263,6 +263,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.DEVICE_PROFILE, operation, entityId, deviceProfile);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
+ return;
}
callback.onSuccess(ValidationResult.ok(deviceProfile));
}
@@ -281,6 +282,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.ASSET_PROFILE, operation, entityId, assetProfile);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
+ return;
}
callback.onSuccess(ValidationResult.ok(assetProfile));
}
@@ -293,6 +295,7 @@ public class AccessValidator {
} else {
if (!operation.equals(Operation.READ_TELEMETRY)) {
callback.onSuccess(ValidationResult.accessDenied("Allowed only READ_TELEMETRY operation!"));
+ return;
}
ApiUsageState apiUsageState = apiUsageStateService.findApiUsageStateById(currentUser.getTenantId(), new ApiUsageStateId(entityId.getId()));
if (apiUsageState == null) {
@@ -302,6 +305,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.API_USAGE_STATE, operation, entityId, apiUsageState);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
+ return;
}
callback.onSuccess(ValidationResult.ok(apiUsageState));
}
@@ -320,6 +324,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.OTA_PACKAGE, operation, entityId, otaPackage);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
+ return;
}
callback.onSuccess(ValidationResult.ok(otaPackage));
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
index 4691f4d114..fe02ae5efb 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
@@ -2,30 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.security.jackson2.SecurityJackson2Modules;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Base64;
import java.util.Optional;
-@Slf4j
public class CookieUtils {
- private static final ObjectMapper OBJECT_MAPPER;
-
- static {
- ClassLoader loader = CookieUtils.class.getClassLoader();
- OBJECT_MAPPER = new ObjectMapper();
- OBJECT_MAPPER.registerModules(SecurityJackson2Modules.getModules(loader));
- }
-
public static Optional getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
@@ -61,24 +45,4 @@ public class CookieUtils {
}
}
}
-
- public static String serialize(Object object) {
- try {
- return Base64.getUrlEncoder()
- .encodeToString(OBJECT_MAPPER.writeValueAsBytes(object));
- } catch (JsonProcessingException e) {
- throw new IllegalArgumentException("The given Json object value: "
- + object + " cannot be transformed to a String", e);
- }
- }
-
- public static T deserialize(Cookie cookie, Class cls) {
- byte[] decodedBytes = Base64.getUrlDecoder().decode(cookie.getValue());
- try {
- return OBJECT_MAPPER.readValue(decodedBytes, cls);
- } catch (IOException e) {
- throw new IllegalArgumentException("The given string value: "
- + Arrays.toString(decodedBytes) + " cannot be transformed to Json object", e);
- }
- }
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
index 5bcda9476a..d867dc9645 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
@@ -2,13 +2,34 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
+import lombok.extern.slf4j.Slf4j;
+import org.bouncycastle.crypto.digests.SHA256Digest;
+import org.bouncycastle.crypto.generators.HKDFBytesGenerator;
+import org.bouncycastle.crypto.params.HKDFParameters;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.stereotype.Component;
import org.thingsboard.server.queue.util.TbCoreComponent;
+import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService;
+import javax.crypto.Cipher;
+import javax.crypto.spec.GCMParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+import java.time.Clock;
+import java.util.Arrays;
+import java.util.Base64;
+
+@Slf4j
@Component
@TbCoreComponent
public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository {
@@ -17,10 +38,31 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
public static final String PREV_URI_COOKIE_NAME = "prev_uri";
private static final int cookieExpireSeconds = 180;
+ private static final byte[] KEY_DERIVATION_INFO = "thingsboard-oauth2-authorization-request-cookie".getBytes(StandardCharsets.UTF_8);
+ private static final int KEY_LENGTH = 32;
+ private static final int NONCE_LENGTH = 12;
+ private static final int TAG_LENGTH_BITS = 128;
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
+ .registerModules(SecurityJackson2Modules.getModules(HttpCookieOAuth2AuthorizationRequestRepository.class.getClassLoader()));
+
+ private final JwtSettingsService jwtSettingsService;
+ private final Clock clock;
+ private final SecureRandom secureRandom = new SecureRandom();
+
+ @Autowired
+ public HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService) {
+ this(jwtSettingsService, Clock.systemUTC());
+ }
+
+ HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService, Clock clock) {
+ this.jwtSettingsService = jwtSettingsService;
+ this.clock = clock;
+ }
+
@Override
public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) {
return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME)
- .map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class))
+ .map(this::decrypt)
.orElse(null);
}
@@ -34,7 +76,7 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
if (PrevUriValidator.isValid(prevUri)) {
CookieUtils.addCookie(response, PREV_URI_COOKIE_NAME, prevUri, cookieExpireSeconds);
}
- CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds);
+ CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, encrypt(authorizationRequest), cookieExpireSeconds);
}
@Override
@@ -45,4 +87,56 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) {
CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME);
}
+
+ private String encrypt(OAuth2AuthorizationRequest authorizationRequest) {
+ try {
+ byte[] json = OBJECT_MAPPER.writeValueAsBytes(authorizationRequest);
+ byte[] plaintext = ByteBuffer.allocate(Long.BYTES + json.length).putLong(clock.millis()).put(json).array();
+ byte[] nonce = new byte[NONCE_LENGTH];
+ secureRandom.nextBytes(nonce);
+ byte[] ciphertext = initCipher(Cipher.ENCRYPT_MODE, nonce).doFinal(plaintext);
+ byte[] envelope = ByteBuffer.allocate(NONCE_LENGTH + ciphertext.length).put(nonce).put(ciphertext).array();
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(envelope);
+ } catch (Exception e) {
+ throw new IllegalStateException("Failed to encrypt OAuth2 authorization request", e);
+ }
+ }
+
+ private OAuth2AuthorizationRequest decrypt(Cookie cookie) {
+ try {
+ byte[] envelope = Base64.getUrlDecoder().decode(cookie.getValue());
+ if (envelope.length < NONCE_LENGTH + TAG_LENGTH_BITS / Byte.SIZE + Long.BYTES) {
+ log.debug("Ignoring OAuth2 authorization request cookie: too short");
+ return null;
+ }
+ byte[] nonce = Arrays.copyOf(envelope, NONCE_LENGTH);
+ byte[] plaintext = initCipher(Cipher.DECRYPT_MODE, nonce).doFinal(envelope, NONCE_LENGTH, envelope.length - NONCE_LENGTH);
+ ByteBuffer buffer = ByteBuffer.wrap(plaintext);
+ long issuedAt = buffer.getLong();
+ if (clock.millis() - issuedAt > cookieExpireSeconds * 1000L) {
+ log.debug("Ignoring OAuth2 authorization request cookie: expired");
+ return null;
+ }
+ return OBJECT_MAPPER.readValue(plaintext, Long.BYTES, plaintext.length - Long.BYTES, OAuth2AuthorizationRequest.class);
+ } catch (Exception e) {
+ log.debug("Ignoring invalid OAuth2 authorization request cookie: {}", e.getClass().getSimpleName());
+ return null;
+ }
+ }
+
+ private Cipher initCipher(int mode, byte[] nonce) throws GeneralSecurityException {
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(mode, new SecretKeySpec(deriveKey(), "AES"), new GCMParameterSpec(TAG_LENGTH_BITS, nonce));
+ return cipher;
+ }
+
+ private byte[] deriveKey() {
+ byte[] signingKey = Base64.getDecoder().decode(jwtSettingsService.getJwtSettings().getTokenSigningKey());
+ HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest());
+ hkdf.init(new HKDFParameters(signingKey, null, KEY_DERIVATION_INFO));
+ byte[] key = new byte[KEY_LENGTH];
+ hkdf.generateBytes(key, 0, KEY_LENGTH);
+ return key;
+ }
+
}
diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
index 09c17c11e8..ba9de0f598 100644
--- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
+++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
@@ -19,7 +19,6 @@ import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Customer;
-import org.thingsboard.server.common.data.DashboardInfo;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.alarm.AlarmInfo;
@@ -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> alreadyExistingEntities = new HashMap<>();
-
- //TODO: check other entities.
+ SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) {
+ //TODO: pre-validate what still only fails at provision time: customer users (unique by email),
+ // alarm rules and calculated fields.
List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() {
});
- if (!ruleChains.isEmpty()) {
- for (ReferenceableEntityDefinition ruleChain : ruleChains) {
- List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData();
- if (savedRuleChains != null && !savedRuleChains.isEmpty()) {
- alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0));
- }
- }
- }
-
List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() {
});
deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class));
- // Validate that entities with such name does not exist entities
- if (!deviceProfiles.isEmpty()) {
- for (DeviceProfile deviceProfile : deviceProfiles) {
- DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName());
- if (savedProfile != null) {
- alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile);
- }
- }
- }
-
List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() {
});
assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class));
- // Validate that entities with such name does not exist entities
- if (!assetProfiles.isEmpty()) {
- for (AssetProfile assetProfile : assetProfiles) {
- AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName());
- if (savedProfile != null) {
- alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile);
- }
+ List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() {
+ });
+ List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
+ });
+ List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() {
+ });
+ List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() {
+ });
+ List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() {
+ });
+
+ // Insertion ordered, so that the reported sections keep the order the entities are provisioned in.
+ Map> conflicts = new LinkedHashMap<>();
+ collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains);
+ collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName,
+ name -> deviceProfileService.findDeviceProfileByName(tenantId, name));
+ collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName,
+ name -> assetProfileService.findAssetProfileByName(tenantId, name));
+ collectConflicts(conflicts, customers,
+ title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null));
+ collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name));
+ collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name));
+ collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title));
+ collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name));
+
+ if (conflicts.isEmpty()) {
+ return SolutionValidationResult.passed();
+ }
+ StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE);
+ conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions));
+ if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) {
+ details.append(System.lineSeparator()).append(TRUNCATION_NOTE);
+ }
+
+ return SolutionValidationResult.conflictsFound(details.toString());
+ }
+
+ private static SolutionInstallResponse conflictResponse(String conflictReport) {
+ SolutionInstallResponse response = new SolutionInstallResponse();
+ response.setSuccess(false);
+ response.setDetails(conflictReport);
+ return response;
+ }
+
+ /**
+ * The entity type and the name both come from the definition, so a list can not end up checked against the
+ * wrong type by mistake.
+ */
+ private void collectConflicts(Map> conflicts, List extends EntityDefinition> definitions,
+ Function lookup) {
+ Set checked = new HashSet<>();
+ for (EntityDefinition definition : definitions) {
+ if (checked.add(definition.getName())) {
+ collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup);
}
}
+ }
- List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
- });
- if (!dashboards.isEmpty()) {
- for (DashboardDefinition dashboard : dashboards) {
- List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData();
- if (savedDashboards != null && !savedDashboards.isEmpty()) {
- alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0));
- }
+ private void collectConflicts(Map> conflicts, EntityType entityType, List definitions,
+ Function nameExtractor, Function lookup) {
+ Set checked = new HashSet<>();
+ for (T definition : definitions) {
+ String name = nameExtractor.apply(definition);
+ if (checked.add(name)) {
+ collectConflict(conflicts, entityType, name, lookup);
}
}
- if (!alreadyExistingEntities.isEmpty()) {
- SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse();
- StringBuilder detailsBuilder = new StringBuilder();
- detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator());
- alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ")
- .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";")
- .append(System.lineSeparator()).append(System.lineSeparator()));
- solutionInstallResponse.setSuccess(false);
- solutionInstallResponse.setDetails(detailsBuilder.toString());
- return solutionInstallResponse;
- } else {
- return null;
+ }
+
+ private void collectConflict(Map> conflicts, EntityType entityType, String name,
+ Function lookup) {
+ if (StringUtils.isEmpty(name)) {
+ return;
+ }
+ HasName existing = lookup.apply(name);
+ if (existing != null) {
+ conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName()));
+ }
+ }
+
+ /**
+ * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will
+ * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE.
+ */
+ private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir,
+ List definitions) {
+ Set checked = new HashSet<>();
+ for (ReferenceableEntityDefinition definition : definitions) {
+ if (StringUtils.isEmpty(definition.getFile())) {
+ continue;
+ }
+ Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile());
+ if (!Files.exists(ruleChainPath)) {
+ // provisionRuleChains logs and skips such a definition, so there is nothing to validate
+ continue;
+ }
+ JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain");
+ if (ruleChain == null || !ruleChain.hasNonNull("name")) {
+ continue;
+ }
+ RuleChainType type = ruleChain.hasNonNull("type")
+ ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE;
+ String name = ruleChain.get("name").asText();
+ if (!checked.add(type + name)) {
+ continue;
+ }
+ collectConflict(conflicts, EntityType.RULE_CHAIN, name,
+ ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name)
+ .stream().findFirst().orElse(null));
}
}
+ /**
+ * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random}
+ * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of
+ * every other entity are used as written, placeholder included, and must be looked up as is.
+ */
+ private static boolean isRandomizedCustomerTitle(String title) {
+ return title.contains(RANDOM_PLACEHOLDER);
+ }
+
+ private static String quoted(String value) {
+ return "'" + value + "'";
+ }
+
+ /**
+ * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads,
+ * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE}
+ * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of
+ * that type is not complete.
+ */
+ private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) {
+ details.append("- **").append(entityType.getNormalName()).append("**: ")
+ .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", ")));
+ if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) {
+ details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE)
+ .append(" more (").append(conflictDescriptions.size()).append(" in total)");
+ }
+ details.append(System.lineSeparator());
+ }
+
private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) {
SolutionInstallContext ctx = new SolutionInstallContext(tenantId, solutionId, tempDir, user, new TenantSolutionTemplateInstructions());
@@ -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 loadEntityIfFileExists(Path tempDir, String fileName, Class 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);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java
new file mode 100644
index 0000000000..4b6b07c54b
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java
@@ -0,0 +1,30 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+package org.thingsboard.server.service.solutions.data;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+/**
+ * The outcome of validating a solution template before anything is created: either the install can go ahead, or the
+ * entities of the tenant the template clashes with, reported as the markdown the install dialog renders.
+ */
+@Getter
+@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
+public class SolutionValidationResult {
+
+ private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, "");
+
+ private final boolean passed;
+ private final String conflictReport;
+
+ public static SolutionValidationResult passed() {
+ return PASSED;
+ }
+
+ public static SolutionValidationResult conflictsFound(String conflictReport) {
+ return new SolutionValidationResult(false, conflictReport);
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java b/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java
index 54c5d271e1..da1a748c37 100644
--- a/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java
+++ b/application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java
@@ -19,7 +19,9 @@ import org.thingsboard.server.common.data.kv.ReadTsKvQuery;
import org.thingsboard.server.common.data.kv.TsKvEntry;
import org.thingsboard.server.dao.timeseries.TimeseriesService;
import org.thingsboard.server.service.security.AccessValidator;
+import org.thingsboard.server.service.security.ValidationCallback;
import org.thingsboard.server.service.security.ValidationResult;
+import org.thingsboard.server.service.security.ValidationResultCode;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.permission.Operation;
@@ -42,6 +44,10 @@ public class DefaultTbTelemetryService implements TbTelemetryService {
accessValidator.validate(currentUser, Operation.READ_TELEMETRY, entityId, new FutureCallback<>() {
@Override
public void onSuccess(ValidationResult validationResult) {
+ if (validationResult.getResultCode() != ValidationResultCode.OK) {
+ onFailure(ValidationCallback.getException(validationResult));
+ return;
+ }
try {
AggregationParams params;
if (Aggregation.NONE.equals(agg)) {
diff --git a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java
index 71f4e73929..15e470085b 100644
--- a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java
+++ b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java
@@ -882,72 +882,36 @@ public class DefaultWebSocketService implements WebSocketService {
}, executor);
}
- private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List keys, final FutureCallback> callback) {
- return new FutureCallback() {
- @Override
- public void onSuccess(@Nullable ValidationResult result) {
- List>> futures = new ArrayList<>();
- for (AttributeScope scope : AttributeScope.values()) {
- futures.add(attributesService.find(tenantId, entityId, scope, keys));
- }
-
- ListenableFuture> future = mergeAllAttributesFutures(futures);
- Futures.addCallback(future, callback, MoreExecutors.directExecutor());
+ private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List keys, final FutureCallback> callback) {
+ return on(r -> {
+ List>> futures = new ArrayList<>();
+ for (AttributeScope scope : AttributeScope.values()) {
+ futures.add(attributesService.find(tenantId, entityId, scope, keys));
}
- @Override
- public void onFailure(Throwable t) {
- callback.onFailure(t);
- }
- };
+ ListenableFuture> future = mergeAllAttributesFutures(futures);
+ Futures.addCallback(future, callback, MoreExecutors.directExecutor());
+ }, callback::onFailure);
}
- private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List keys, final FutureCallback> callback) {
- return new FutureCallback() {
- @Override
- public void onSuccess(@Nullable ValidationResult result) {
- Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor());
- }
-
- @Override
- public void onFailure(Throwable t) {
- callback.onFailure(t);
- }
- };
+ private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List keys, final FutureCallback> callback) {
+ return on(r -> Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor()), callback::onFailure);
}
- private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback> callback) {
- return new FutureCallback() {
- @Override
- public void onSuccess(@Nullable ValidationResult result) {
- List>> futures = new ArrayList<>();
- for (AttributeScope scope : AttributeScope.values()) {
- futures.add(attributesService.findAll(tenantId, entityId, scope));
- }
-
- ListenableFuture> future = mergeAllAttributesFutures(futures);
- Futures.addCallback(future, callback, MoreExecutors.directExecutor());
+ private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback> callback) {
+ return on(r -> {
+ List>> futures = new ArrayList<>();
+ for (AttributeScope scope : AttributeScope.values()) {
+ futures.add(attributesService.findAll(tenantId, entityId, scope));
}
- @Override
- public void onFailure(Throwable t) {
- callback.onFailure(t);
- }
- };
+ ListenableFuture> future = mergeAllAttributesFutures(futures);
+ Futures.addCallback(future, callback, MoreExecutors.directExecutor());
+ }, callback::onFailure);
}
- private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback> callback) {
- return new FutureCallback() {
- @Override
- public void onSuccess(@Nullable ValidationResult result) {
- Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor());
- }
-
- @Override
- public void onFailure(Throwable t) {
- callback.onFailure(t);
- }
- };
+ private FutureCallback getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback> callback) {
+ return on(r -> Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()), callback::onFailure);
}
private FutureCallback on(Consumer success, Consumer failure) {
diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml
index 2de4c21c8a..a527a4108c 100644
--- a/application/src/main/resources/thingsboard.yml
+++ b/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:
diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
index aaa878193f..6b7b0201f4 100644
--- a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
+++ b/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));
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java
index 9421e33f54..9ca0ba2fd0 100644
--- a/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java
+++ b/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 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());
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java b/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java
index 4a9f2673a9..1b5817ac21 100644
--- a/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java
+++ b/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.");
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java
index f582f7cd09..9d1c7db552 100644
--- a/application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java
+++ b/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";
diff --git a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java
index 3170d9480f..99b500de1e 100644
--- a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java
+++ b/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 -> {
diff --git a/application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java b/application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java
index e005cb18ff..508492eedb 100644
--- a/application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java
+++ b/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();
diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
index 070eda60d5..9137724ef8 100644
--- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
+++ b/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);
diff --git a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java
index 888a0b31bb..8c73569128 100644
--- a/application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java
+++ b/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 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 devices = new ArrayList<>();
diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java
new file mode 100644
index 0000000000..8b471d0548
--- /dev/null
+++ b/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 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> consumerManager = mock(QueueConsumerManager.class);
+ @SuppressWarnings("unchecked")
+ TbQueueConsumer> 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 sessions() {
+ return field("sessions");
+ }
+
+ private ConcurrentMap sessionsById() {
+ return field("sessionsById");
+ }
+
+ private ConcurrentMap> edgeEventChecks() {
+ return field("sessionEdgeEventChecks");
+ }
+
+ private Map newEvents() {
+ return field("sessionNewEvents");
+ }
+
+ private ConcurrentMap migrationProcessed() {
+ return field("edgeEventsMigrationProcessed");
+ }
+
+ @SuppressWarnings("unchecked")
+ private T field(String name) {
+ return (T) ReflectionTestUtils.getField(service, name);
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java
index 9ee8632f45..758a0801b7 100644
--- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java
+++ b/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> consumerManager = mock(QueueConsumerManager.class);
- TbQueueConsumer> 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> consumerManager = mock(QueueConsumerManager.class);
- TbQueueConsumer> 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 activeStateWrite() {
@@ -408,11 +322,6 @@ public class EdgeGrpcServiceTest {
return (ConcurrentMap) ReflectionTestUtils.getField(edgeGrpcService, "sessions");
}
- @SuppressWarnings("unchecked")
- private ConcurrentMap> sessionEdgeEventChecks() {
- return (ConcurrentMap>) ReflectionTestUtils.getField(edgeGrpcService, "sessionEdgeEventChecks");
- }
-
private ArgumentMatcher inactiveStateWrite() {
return request -> request != null
&& edgeId.equals(request.getEntityId())
diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
index e0efa4575b..559215e526 100644
--- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
+++ b/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();
diff --git a/application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java b/application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java
index 89f939a9a6..d34bb6e98a 100644
--- a/application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java
+++ b/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);
diff --git a/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java b/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java
index aae8b1c496..4268694f9b 100644
--- a/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java
+++ b/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> 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> 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> 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> 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> 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> 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> 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> 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> 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> 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
diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java
index 90c2888a51..e973ee13dc 100644
--- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java
+++ b/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, "{}");
diff --git a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java
index 00ff00b9e4..2ab081f686 100644
--- a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java
+++ b/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, "{}");
diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java
deleted file mode 100644
index 9bae84d44d..0000000000
--- a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java
+++ /dev/null
@@ -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 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());
- }
-
-}
\ No newline at end of file
diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java
index 7cb38fa428..4b292712af 100644
--- a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java
+++ b/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 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 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);
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java
new file mode 100644
index 0000000000..d65868a7fb
--- /dev/null
+++ b/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 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);
+ }
+
+}
diff --git a/common/actor/pom.xml b/common/actor/pom.xml
index 7e6bbe85ff..32255fa155 100644
--- a/common/actor/pom.xml
+++ b/common/actor/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/cache/pom.xml b/common/cache/pom.xml
index cbfe90440b..a70bdc5b66 100644
--- a/common/cache/pom.xml
+++ b/common/cache/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/cluster-api/pom.xml b/common/cluster-api/pom.xml
index 06552c67ae..e28c419b43 100644
--- a/common/cluster-api/pom.xml
+++ b/common/cluster-api/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml
index 74e2777c4e..395d041726 100644
--- a/common/coap-server/pom.xml
+++ b/common/coap-server/pom.xml
@@ -11,7 +11,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/dao-api/pom.xml b/common/dao-api/pom.xml
index e91cb60df1..a99d0be727 100644
--- a/common/dao-api/pom.xml
+++ b/common/dao-api/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
@@ -41,6 +41,10 @@
com.google.guavaguava
+
+ org.checkerframework
+ checker-qual
+ jakarta.annotationjakarta.annotation-api
diff --git a/common/data/pom.xml b/common/data/pom.xml
index 5b9a8cc97c..191efcd66b 100644
--- a/common/data/pom.xml
+++ b/common/data/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java
deleted file mode 100644
index 654f36f31e..0000000000
--- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DashboardInstalledItemDescriptor.java
+++ /dev/null
@@ -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;
-
-}
diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java
index 0ef245c0ac..ca8b3a1b83 100644
--- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java
+++ b/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),
diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java
index 9b6e376365..5a6b04f1ac 100644
--- a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java
+++ b/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;
}
}
diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java
index 35073196c2..dbfe8ad4ee 100644
--- a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java
+++ b/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 pushDeleteNotificationToCoreStatuses = List.of(
+ private static final List 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();
}
}
}
diff --git a/common/discovery-api/pom.xml b/common/discovery-api/pom.xml
index 6b12557443..5abb4d44e5 100644
--- a/common/discovery-api/pom.xml
+++ b/common/discovery-api/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/edge-api/pom.xml b/common/edge-api/pom.xml
index 51c96c6f37..74f3ca69ef 100644
--- a/common/edge-api/pom.xml
+++ b/common/edge-api/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto
index cddeb0191a..6e90937b6d 100644
--- a/common/edge-api/src/main/proto/edge.proto
+++ b/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 {
diff --git a/common/edqs/pom.xml b/common/edqs/pom.xml
index e61a27a8a8..7ae1bf1598 100644
--- a/common/edqs/pom.xml
+++ b/common/edqs/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/message/pom.xml b/common/message/pom.xml
index 417916e518..8fce218c6a 100644
--- a/common/message/pom.xml
+++ b/common/message/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/pom.xml b/common/pom.xml
index c533e1554a..dd63b4e36f 100644
--- a/common/pom.xml
+++ b/common/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTthingsboardcommon
diff --git a/common/proto/pom.xml b/common/proto/pom.xml
index 7e835835fc..142cd17a6f 100644
--- a/common/proto/pom.xml
+++ b/common/proto/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/queue/pom.xml b/common/queue/pom.xml
index 4a340a96ec..58cddea1ea 100644
--- a/common/queue/pom.xml
+++ b/common/queue/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
@@ -123,6 +123,11 @@
awaitilitytest
+
+ org.apache.curator
+ curator-test
+ test
+
diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java
index 5617a3d148..ff1746d54c 100644
--- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java
+++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java
@@ -96,7 +96,7 @@ public class HashPartitionService implements PartitionService {
private final ConcurrentMap tenantRoutingInfoMap = new ConcurrentHashMap<>();
- private List currentOtherServices;
+ private volatile List currentOtherServices;
private final Map> tbTransportServicesByType = new HashMap<>();
private volatile Map> 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 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 getAllServices(ServiceType serviceType) {
Set result = getOtherServices(serviceType);
diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java
index 73e585568b..73ccf32373 100644
--- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java
+++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java
@@ -48,6 +48,12 @@ public interface PartitionService {
*/
Set 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 getAllServices(ServiceType serviceType);
Set getOtherServices(ServiceType serviceType);
diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java
index 512bac6edd..1233e2878a 100644
--- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java
+++ b/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 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;
diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java
index 55edc5e4ad..37af643ff0 100644
--- a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java
+++ b/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 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);
diff --git a/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java b/common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java
new file mode 100644
index 0000000000..380d13176d
--- /dev/null
+++ b/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 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 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());
+ });
+ }
+
+}
diff --git a/common/script/pom.xml b/common/script/pom.xml
index 475151e2a9..0aaf8d8b24 100644
--- a/common/script/pom.xml
+++ b/common/script/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/script/remote-js-client/pom.xml b/common/script/remote-js-client/pom.xml
index eac7a8561d..d09969f843 100644
--- a/common/script/remote-js-client/pom.xml
+++ b/common/script/remote-js-client/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTscriptorg.thingsboard.common.script
diff --git a/common/script/script-api/pom.xml b/common/script/script-api/pom.xml
index 573f4b7ff4..cc8779b22c 100644
--- a/common/script/script-api/pom.xml
+++ b/common/script/script-api/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTscriptorg.thingsboard.common.script
diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java
index cbdd753346..8075e70fe4 100644
--- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java
+++ b/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 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();
}
}
diff --git a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java
new file mode 100644
index 0000000000..673e06d5a8
--- /dev/null
+++ b/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);
+ }
+
+}
diff --git a/common/stats/pom.xml b/common/stats/pom.xml
index 771d46eaaf..a5a98e3402 100644
--- a/common/stats/pom.xml
+++ b/common/stats/pom.xml
@@ -11,7 +11,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/transport/coap/pom.xml b/common/transport/coap/pom.xml
index 6c05a559b8..7b1a0f8abe 100644
--- a/common/transport/coap/pom.xml
+++ b/common/transport/coap/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTtransportorg.thingsboard.common.transport
diff --git a/common/transport/http/pom.xml b/common/transport/http/pom.xml
index cb27c74bfa..16c955712b 100644
--- a/common/transport/http/pom.xml
+++ b/common/transport/http/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTtransportorg.thingsboard.common.transport
diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml
index 271bd9dbc0..7bf3023aa6 100644
--- a/common/transport/lwm2m/pom.xml
+++ b/common/transport/lwm2m/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTtransportorg.thingsboard.common.transport
diff --git a/common/transport/mqtt/pom.xml b/common/transport/mqtt/pom.xml
index da1fab79aa..feabe3f909 100644
--- a/common/transport/mqtt/pom.xml
+++ b/common/transport/mqtt/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTtransportorg.thingsboard.common.transport
diff --git a/common/transport/pom.xml b/common/transport/pom.xml
index 949f5da4ba..8078084815 100644
--- a/common/transport/pom.xml
+++ b/common/transport/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/transport/snmp/pom.xml b/common/transport/snmp/pom.xml
index b372d17b11..563d582719 100644
--- a/common/transport/snmp/pom.xml
+++ b/common/transport/snmp/pom.xml
@@ -10,7 +10,7 @@
org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTtransport
diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml
index 021ef4ee16..6e03562191 100644
--- a/common/transport/transport-api/pom.xml
+++ b/common/transport/transport-api/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard.common
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTtransportorg.thingsboard.common.transport
diff --git a/common/util/pom.xml b/common/util/pom.xml
index eaa4edfaf8..034569ab4e 100644
--- a/common/util/pom.xml
+++ b/common/util/pom.xml
@@ -9,7 +9,7 @@
4.0.0org.thingsboard
- 4.2.2.6-SNAPSHOT
+ 4.2.2.7-SNAPSHOTcommonorg.thingsboard.common
diff --git a/common/util/src/main/java/org/thingsboard/common/util/SetCache.java b/common/util/src/main/java/org/thingsboard/common/util/SetCache.java
index b191709740..5322ebc4ef 100644
--- a/common/util/src/main/java/org/thingsboard/common/util/SetCache.java
+++ b/common/util/src/main/java/org/thingsboard/common/util/SetCache.java
@@ -14,9 +14,19 @@ public class SetCache {
private final Cache cache;
public SetCache(long valueTtlMs) {
- this.cache = Caffeine.newBuilder()
- .expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS)
- .build();
+ this(Caffeine.newBuilder().expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS));
+ }
+
+ private SetCache(Caffeine