diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupService.java index 780dcbe196..3eff5440d5 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupService.java @@ -72,8 +72,10 @@ public class DefaultZombieSessionCleanupService implements ZombieSessionCleanupS private void cleanupZombieSessions() { try { + // remove by identity: the edge may have reconnected since the zombie scan, and that newer + // session must not be evicted by the cleanup of the one it replaced tryToDestroyZombieSessions(getZombieSessions(edgeSessionsHolder.getSessions().values()), - s -> edgeSessionsHolder.removeByEdgeId(s.getState().getEdge().getId())); + s -> edgeSessionsHolder.removeByEdgeIdIfCurrent(s.getState().getEdgeId(), s.getState().getSessionId())); tryToDestroyZombieSessions(getZombieSessions(edgeSessionsHolder.getSessionsById().values()), s -> edgeSessionsHolder.removeBySessionId(s.getState().getSessionId())); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolder.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolder.java index 8881ceb203..6e5837476d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolder.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolder.java @@ -68,11 +68,26 @@ public class EdgeSessionsHolder { return sessions.remove(id); } + /** + * Whether the given session is still the one registered for its edge. A session that has been + * superseded must not arm or run work on the edge's behalf - the session that replaced it owns + * that now - and a plain "some session exists for this edge" check does not catch that. + */ + public boolean isCurrent(EdgeGrpcSessionManager session) { + EdgeSessionState state = session.getState(); + return state != null && sessions.get(state.getEdgeId()) == session; + } + /** * Removes the edge's registered session and returns it, but only if it is still the given session. * Returns null when another session has taken the edge over in the meantime, so that a teardown * racing with a reconnect cannot act on behalf of a session it no longer owns. The check and the * removal are one atomic step. + *

+ * Only cheap non-blocking work may run inside the remapping function: it holds the bin lock of + * {@link #sessions} for this edge, so a slow teardown such as + * {@link EdgeGrpcSessionManager#destroyAndMarkAsZombieIfFailed()} has to be done by the caller + * once compute has returned. */ public EdgeGrpcSessionManager removeByEdgeIdIfCurrent(EdgeId id, UUID sessionId) { AtomicReference removed = new AtomicReference<>(); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/AbstractEdgeGrpcSessionManager.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/AbstractEdgeGrpcSessionManager.java index 0df1af1ada..70bb8d71c9 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/AbstractEdgeGrpcSessionManager.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/AbstractEdgeGrpcSessionManager.java @@ -122,6 +122,11 @@ public abstract class AbstractEdgeGrpcSessionManager extends EdgeGrpcSessionDele session.sendDownlinkMsg(edgeConfigMsg); } + /** + * Stops the session and hands it to the zombie cleanup service if that fails. This can block for + * seconds - the Kafka session gives its consumer executor up to 5s to terminate - so it must never + * be called from inside an {@code EdgeSessionsHolder} remapping function. + */ @Override public void destroyAndMarkAsZombieIfFailed() { EdgeSessionState state = getState(); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/KafkaBasedEdgeGrpcSessionManager.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/KafkaBasedEdgeGrpcSessionManager.java index f42f48421a..da3f33cb91 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/KafkaBasedEdgeGrpcSessionManager.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/KafkaBasedEdgeGrpcSessionManager.java @@ -127,8 +127,8 @@ public class KafkaBasedEdgeGrpcSessionManager extends AbstractEdgeGrpcSessionMan TenantId tenantId = state.getTenantId(); EdgeId edgeId = state.getEdgeId(); - if (!sessions.hasByEdgeId(edgeId)) { - log.debug("[{}] Session was removed and edge event consumer must not be started [{}]", + if (!sessions.isCurrent(this)) { + log.debug("[{}] Session is not current anymore and edge event consumer must not be started [{}]", tenantId, edgeId.getId()); return; } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/PostgresBasedEdgeGrpcSessionManager.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/PostgresBasedEdgeGrpcSessionManager.java index 0190cd2784..6c269ef893 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/PostgresBasedEdgeGrpcSessionManager.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/PostgresBasedEdgeGrpcSessionManager.java @@ -92,8 +92,8 @@ public class PostgresBasedEdgeGrpcSessionManager extends AbstractEdgeGrpcSession EdgeId edgeId = getState().getEdgeId(); TenantId tenantId = getState().getTenantId(); - if (!edgeSessions.hasByEdgeId(edgeId)) { - log.debug("[{}] Session was removed and edge event check schedule must not be started [{}]", + if (!edgeSessions.isCurrent(this)) { + log.debug("[{}] Session is not current anymore and edge event check schedule must not be started [{}]", tenantId, edgeId.getId()); return; } @@ -101,6 +101,11 @@ public class PostgresBasedEdgeGrpcSessionManager extends AbstractEdgeGrpcSession try { newEventsLock.lock(); try { + if (!edgeSessions.isCurrent(this)) { + log.debug("[{}] Session is not current anymore, edge event check must not run for edge [{}]", + tenantId, edgeId.getId()); + return; + } if (!hasNewEvents) { scheduleEdgeEventsCheck(); return; diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupServiceTest.java new file mode 100644 index 0000000000..5c3d75605e --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupServiceTest.java @@ -0,0 +1,131 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.edge.rpc.session; + +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.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.TenantId; +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.service.edge.rpc.EdgeSessionState; +import org.thingsboard.server.service.edge.rpc.session.manager.EdgeGrpcSessionManager; +import org.thingsboard.server.service.edge.rpc.session.manager.KafkaBasedEdgeGrpcSessionManager; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The zombie sweep destroys a session and then removes it from the holder. If the edge reconnects in + * between, the removal must not take the live session with it. + */ +class DefaultZombieSessionCleanupServiceTest { + + private DefaultZombieSessionCleanupService service; + private EdgeSessionsHolder holder; + private Edge edge; + private EdgeId edgeId; + + @BeforeEach + void setUp() { + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + edge.setName("test-edge"); + + holder = new EdgeSessionsHolder(); + service = new DefaultZombieSessionCleanupService(); + ReflectionTestUtils.setField(service, "edgeSessionsHolder", holder); + } + + @AfterEach + void tearDown() { + service.destroy(); + } + + @Test + void cleanupRemovesTheZombieWhenItStillOwnsTheEdge() { + KafkaBasedEdgeGrpcSessionManager zombie = newZombieSession(); + when(zombie.destroy()).thenReturn(true); + holder.put(zombie); + + cleanupZombieSessions(); + + assertThat(holder.getByEdgeId(edgeId)).isNull(); + } + + @Test + void cleanupKeepsASessionThatReconnectedDuringTheSweep() { + KafkaBasedEdgeGrpcSessionManager zombie = newZombieSession(); + EdgeGrpcSessionManager reconnected = newSession(); + holder.put(zombie); + // the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up. + // The sweep also passes over sessionsById, so only the first destroy stands in for the reconnect + AtomicBoolean reconnectPending = new AtomicBoolean(true); + when(zombie.destroy()).thenAnswer(invocation -> { + if (reconnectPending.compareAndSet(true, false)) { + holder.put(reconnected); + } + return true; + }); + + cleanupZombieSessions(); + + assertThat(holder.getByEdgeId(edgeId)) + .as("removing by edge id alone would evict the live session here") + .isSameAs(reconnected); + } + + private void cleanupZombieSessions() { + ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions"); + } + + private EdgeGrpcSessionManager newSession() { + EdgeGrpcSessionManager session = mock(EdgeGrpcSessionManager.class); + when(session.getState()).thenReturn(newState()); + return session; + } + + private KafkaBasedEdgeGrpcSessionManager newZombieSession() { + KafkaBasedEdgeGrpcSessionManager session = mock(KafkaBasedEdgeGrpcSessionManager.class); + when(session.getState()).thenReturn(newState()); + @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 EdgeSessionState newState() { + EdgeSessionState state = new EdgeSessionState(); + state.setEdge(edge); + state.setConnected(false); + return state; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolderTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolderTest.java new file mode 100644 index 0000000000..082aadee83 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolderTest.java @@ -0,0 +1,105 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.edge.rpc.session; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.service.edge.rpc.EdgeSessionState; +import org.thingsboard.server.service.edge.rpc.session.manager.EdgeGrpcSessionManager; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A teardown that races with a reconnect must not act on behalf of the session that has taken the + * edge over: neither by removing it from the holder nor by treating it as current. + */ +class EdgeSessionsHolderTest { + + private EdgeSessionsHolder holder; + private Edge edge; + private EdgeId edgeId; + + @BeforeEach + void setUp() { + holder = new EdgeSessionsHolder(); + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + edge.setName("test-edge"); + } + + @Test + void removeByEdgeIdIfCurrentRemovesTheRegisteredSession() { + EdgeGrpcSessionManager session = newSession(); + holder.put(session); + + EdgeGrpcSessionManager removed = holder.removeByEdgeIdIfCurrent(edgeId, session.getState().getSessionId()); + + assertThat(removed).isSameAs(session); + assertThat(holder.getByEdgeId(edgeId)).isNull(); + } + + @Test + void removeByEdgeIdIfCurrentKeepsTheSessionThatTookTheEdgeOver() { + EdgeGrpcSessionManager first = newSession(); + EdgeGrpcSessionManager second = newSession(); + holder.put(first); + holder.put(second); + + EdgeGrpcSessionManager removed = holder.removeByEdgeIdIfCurrent(edgeId, first.getState().getSessionId()); + + assertThat(removed).as("the superseded session owns nothing to remove").isNull(); + assertThat(holder.getByEdgeId(edgeId)) + .as("the reconnected session stays registered") + .isSameAs(second); + } + + @Test + void isCurrentOnlyForTheSessionRegisteredForTheEdge() { + EdgeGrpcSessionManager first = newSession(); + EdgeGrpcSessionManager second = newSession(); + holder.put(first); + assertThat(holder.isCurrent(first)).isTrue(); + + holder.put(second); + + assertThat(holder.isCurrent(second)).isTrue(); + assertThat(holder.isCurrent(first)) + .as("a presence check would still say true here, which is the bug this guards") + .isFalse(); + } + + @Test + void isCurrentIsFalseWhenTheEdgeHasNoRegisteredSession() { + assertThat(holder.isCurrent(newSession())).isFalse(); + } + + private EdgeGrpcSessionManager newSession() { + EdgeSessionState state = new EdgeSessionState(); + state.setEdge(edge); + EdgeGrpcSessionManager session = mock(EdgeGrpcSessionManager.class); + when(session.getState()).thenReturn(state); + return session; + } + +}