Browse Source

Merge branch 'fix/edge-activity-state-guard-followups-lts-4.2' into fix/edge-activity-state-guard-followups-lts-4.3

Brings the review follow-ups across to lts-4.3, adapted to this branch:

- The disconnect side effects use pushStateEventToRuleEngine here, and
  scheduleDisconnectNotification stays outside the new guard because
  fireDelayedDisconnectNotification re-verifies liveness itself.
- The eviction guard needed no change: lts-4.3 already wraps
  evictServiceIdCacheIfOwnedByThisNode in a !sessions.containsKey check, which is
  what lts-4.2 gained here.
- The rule-engine stubs from the lts-4.2 tests are dropped: lts-4.3 moved the
  notification call out of pushStateEventToRuleEngine into
  notifyEdgeConnectivity, so the push no longer depends on the context mock.
pull/16163/head
Volodymyr Babak 3 months ago
parent
commit
2356a209e1
  1. 39
      application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
  2. 112
      application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java

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

@ -77,7 +77,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function;
import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE;
import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME; import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME;
@ -549,16 +548,24 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
destroySession(toRemove); destroySession(toRemove);
sessionsById.remove(sessionId); sessionsById.remove(sessionId);
TenantId tenantId = toRemove.getEdge().getTenantId(); TenantId tenantId = toRemove.getEdge().getTenantId();
// A newer session on another node may have already claimed this edge and set active=true. // The edge may already have been claimed by a newer session - on this node (a replacement that
// Clearing the flag here would leave the edge marked inactive while it is in fact connected, // landed while this stale callback was tearing its own session down) or on another live node.
// which silently drops every downlink event that is not queued for offline edges. // Either way the edge is connected, so none of the disconnect side effects apply:
// When ownership is unknown (no cache entry) fall through and persist the inactive state. // - clearing the flag makes saveEdgeEvent drop assignment events until a full sync;
if (!isOwnedByAnotherNode(edgeId)) { // - 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.
// Ownership being unknown (no cache entry) still counts as disconnected, so a genuinely offline
// edge is always marked inactive.
if (!sessions.containsKey(edgeId) && !isOwnedByAnotherNode(edgeId)) {
save(tenantId, edgeId, ACTIVITY_STATE, false); save(tenantId, edgeId, ACTIVITY_STATE, false);
long lastDisconnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs);
pushStateEventToRuleEngine(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
} }
long lastDisconnectTs = System.currentTimeMillis(); // Left outside the guard on purpose: fireDelayedDisconnectNotification re-verifies liveness
save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); // against the local sessions and the cluster-wide cache before it fires.
pushStateEventToRuleEngine(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
scheduleDisconnectNotification(edge); scheduleDisconnectNotification(edge);
cancelScheduleEdgeEventsCheck(edgeId); cancelScheduleEdgeEventsCheck(edgeId);
} else { } else {
@ -605,6 +612,11 @@ 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 // - 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 // (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. // 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) { private boolean isOwnedByAnotherNode(EdgeId edgeId) {
TbCacheValueWrapper<String> wrapper = edgeIdServiceIdCache.get(edgeId); TbCacheValueWrapper<String> wrapper = edgeIdServiceIdCache.get(edgeId);
if (wrapper == null) { if (wrapper == null) {
@ -836,7 +848,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
private void cleanupZombieSessions() { private void cleanupZombieSessions() {
try { try {
tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId())); // 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));
tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId()));
zombieSessions.removeIf(zombie -> { zombieSessions.removeIf(zombie -> {
@ -865,11 +880,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
return result; return result;
} }
private void tryToDestroyZombieSessions(List<EdgeGrpcSession> sessionsToRemove, Function<EdgeGrpcSession, EdgeGrpcSession> removeFunc) { private void tryToDestroyZombieSessions(List<EdgeGrpcSession> sessionsToRemove, Consumer<EdgeGrpcSession> removeFunc) {
for (EdgeGrpcSession toRemove : sessionsToRemove) { for (EdgeGrpcSession toRemove : sessionsToRemove) {
log.info("[{}] Destroying session for edge because edge is not connected", toRemove.getEdge().getId()); log.info("[{}] Destroying session for edge because edge is not connected", toRemove.getEdge().getId());
if (toRemove.destroy()) { if (toRemove.destroy()) {
removeFunc.apply(toRemove); removeFunc.accept(toRemove);
} }
} }
} }

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

@ -6,6 +6,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatcher; import org.mockito.ArgumentMatcher;
import org.mockito.InOrder;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
@ -13,25 +14,36 @@ import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; import org.thingsboard.server.cache.SimpleTbCacheValueWrapper;
import org.thingsboard.server.cache.TbTransactionalCache; 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.edge.Edge;
import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger; import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger;
import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger; import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor;
import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import org.thingsboard.server.service.edge.EdgeContextComponent; import org.thingsboard.server.service.edge.EdgeContextComponent;
import org.thingsboard.server.service.edge.rpc.EdgeEventStorageSettings;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
@ -60,9 +72,18 @@ public class EdgeGrpcServiceTest {
@Mock @Mock
private TelemetrySubscriptionService tsSubService; private TelemetrySubscriptionService tsSubService;
@Mock
private TbClusterService clusterService;
@Mock @Mock
private PartitionService partitionService; private PartitionService partitionService;
@Mock
private EdgeEventStorageSettings edgeEventStorageSettings;
@Mock
private ScheduledExecutorService edgeEventProcessingExecutorService;
@InjectMocks @InjectMocks
private EdgeGrpcService edgeGrpcService; private EdgeGrpcService edgeGrpcService;
@ -217,6 +238,80 @@ public class EdgeGrpcServiceTest {
verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite()));
} }
@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.
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;
});
sessions().put(edgeId, stale);
onEdgeDisconnect(sessionId);
verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite()));
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
verify(edgeIdServiceIdCache, never()).evict(edgeId);
}
@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));
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));
onEdgeDisconnect(stub.sessionId());
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.
EdgeGrpcSession session = mock(EdgeGrpcSession.class);
when(session.getSessionId()).thenReturn(UUID.randomUUID());
when(session.getEdge()).thenReturn(edge);
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(ctx.getEdgeEventStorageSettings()).thenReturn(edgeEventStorageSettings);
ReflectionTestUtils.setField(edgeGrpcService, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService);
when(edgeEventProcessingExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
.thenAnswer(invocation -> mock(ScheduledFuture.class));
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeConnect", edgeId, session);
InOrder inOrder = inOrder(edgeIdServiceIdCache, tsSubService);
inOrder.verify(edgeIdServiceIdCache).put(edgeId, THIS_NODE);
inOrder.verify(tsSubService).saveAttributes(argThat(activeStateWrite()));
}
// --- service-id cache eviction guard ---
@Test @Test
public void givenEdgeOwnedByThisNode_whenDisconnect_thenInactiveStateIsPersisted() { public void givenEdgeOwnedByThisNode_whenDisconnect_thenInactiveStateIsPersisted() {
UUID sessionId = UUID.randomUUID(); UUID sessionId = UUID.randomUUID();
@ -246,6 +341,23 @@ public class EdgeGrpcServiceTest {
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId); 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) {
}
private ArgumentMatcher<AttributesSaveRequest> activeStateWrite() {
return request -> request != null
&& edgeId.equals(request.getEntityId())
&& request.getEntries().stream().anyMatch(entry ->
ACTIVITY_STATE.equals(entry.getKey())
&& Boolean.TRUE.equals(entry.getBooleanValue().orElse(null)));
}
private EdgeGrpcSession sessionFor(UUID sessionId) { private EdgeGrpcSession sessionFor(UUID sessionId) {
EdgeGrpcSession session = mock(EdgeGrpcSession.class); EdgeGrpcSession session = mock(EdgeGrpcSession.class);
when(session.getSessionId()).thenReturn(sessionId); when(session.getSessionId()).thenReturn(sessionId);

Loading…
Cancel
Save