Browse Source

Merge branch 'fix/edge-event-check-lost-on-reconnect-lts-4.3' into fix/edge-event-check-lost-on-reconnect-master

# Conflicts:
#	application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
pull/16094/head
Nikita Mazurenko 3 months ago
parent
commit
269bc8dc73
  1. 4
      application/src/main/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupService.java
  2. 15
      application/src/main/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolder.java
  3. 5
      application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/AbstractEdgeGrpcSessionManager.java
  4. 4
      application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/KafkaBasedEdgeGrpcSessionManager.java
  5. 9
      application/src/main/java/org/thingsboard/server/service/edge/rpc/session/manager/PostgresBasedEdgeGrpcSessionManager.java
  6. 131
      application/src/test/java/org/thingsboard/server/service/edge/rpc/session/DefaultZombieSessionCleanupServiceTest.java
  7. 105
      application/src/test/java/org/thingsboard/server/service/edge/rpc/session/EdgeSessionsHolderTest.java

4
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()));

15
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.
* <p>
* 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<EdgeGrpcSessionManager> removed = new AtomicReference<>();

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

4
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;
}

9
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;

131
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<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class);
@SuppressWarnings("unchecked")
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class);
when(consumerManager.getConsumer()).thenReturn(consumer);
when(consumer.isStopped()).thenReturn(false);
when(session.getConsumer()).thenReturn(consumerManager);
return session;
}
private EdgeSessionState newState() {
EdgeSessionState state = new EdgeSessionState();
state.setEdge(edge);
state.setConnected(false);
return state;
}
}

105
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;
}
}
Loading…
Cancel
Save