From 7fa8edfd0e66acec6b841006dc74b14865224a5f Mon Sep 17 00:00:00 2001 From: Volodymyr Babak Date: Thu, 17 Sep 2026 10:05:40 +0300 Subject: [PATCH] fix: do not clear edge activity state when session moved to another node onEdgeDisconnect persisted active=false based only on this node's in-memory session map. When an edge drops and reconnects to a different TB-Core node, the new node sets active=true while the old node writes active=false whenever it finally notices its dead stream. If the stale write lands last, the edge stays marked inactive while its gRPC session is alive. That flag is not only a status indicator: saveEdgeEvent() consults it before queueing any server-to-edge event, and actions that are not on the offline allowlist - device and entity-group assignments among them - are dropped outright rather than queued. A stale active=false therefore makes assignments silently never reach the edge, with a full "Sync Edge" as the only recovery. - Guard the write with the cluster-wide service-id cache, skipping it only when another node is the recorded owner and that node is still a live TB_CORE service. An absent entry means ownership is unknown, not claimed elsewhere, so that case still persists the inactive state; and a node that died without evicting its claim cannot leave the edge marked active forever. - Publish the ownership claim before writing active=true in onEdgeConnect, so a disconnect callback on the node the edge just left cannot read a stale owner. - Only evict the service-id cache entry when it still points at this node. A stale callback would otherwise wipe the live owner's claim and defeat the guard above for any later disconnect. - Remove the session atomically in onEdgeDisconnect. get() and remove() were not atomic, so a session replaced between the two was dropped from the map, torn down and marked inactive by the stale callback even though it was the live one. LAST_DISCONNECT_TIME and the rule-engine DISCONNECT_EVENT are intentionally left unguarded - they are accurate statements about this session, and the timestamps are the main diagnostic signal for flapping edges. Backport of thingsboard/thingsboard#16155 to lts-4.2, which has no disconnect notification debounce and therefore none of the ownership helpers the 4.3 change builds on; they are introduced here. --- .../service/edge/rpc/EdgeGrpcService.java | 59 ++++- .../service/edge/rpc/EdgeGrpcServiceTest.java | 221 ++++++++++++++++++ 2 files changed, 275 insertions(+), 5 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java 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 e1211c53a7..9e18ed7e2f 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 @@ -37,6 +37,7 @@ import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.TimeseriesSaveRequest; import org.thingsboard.server.cache.TbTransactionalCache; +import org.thingsboard.server.cache.TbCacheValueWrapper; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.DataConstants; @@ -58,11 +59,13 @@ import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; import org.thingsboard.server.common.msg.edge.EdgeSessionMsg; import org.thingsboard.server.common.msg.edge.FromEdgeSyncResponse; import org.thingsboard.server.common.msg.edge.ToEdgeSyncRequest; +import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.gen.edge.v1.EdgeRpcServiceGrpc; import org.thingsboard.server.gen.edge.v1.RequestMsg; import org.thingsboard.server.gen.edge.v1.ResponseMsg; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.queue.discovery.TopicService; +import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.kafka.KafkaAdmin; import org.thingsboard.server.queue.provider.TbCoreQueueFactory; import org.thingsboard.server.queue.util.AfterStartUp; @@ -152,6 +155,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Autowired private TbTransactionalCache edgeIdServiceIdCache; + @Autowired + private PartitionService partitionService; + @Autowired private TopicService topicService; @@ -382,10 +388,13 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } + // Claim ownership before writing the active state, not after: onEdgeDisconnect on the node this edge + // just left reads the cache to decide whether to clear the flag, so publishing the claim first keeps + // it from seeing a stale owner and clearing a state we have already set. + edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId()); save(tenantId, edgeId, ACTIVITY_STATE, true); long lastConnectTs = System.currentTimeMillis(); save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs); - edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId()); pushRuleEngineMessage(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); cancelScheduleEdgeEventsCheck(edgeId); edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); @@ -533,8 +542,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = edge.getId(); log.info("[{}][{}] edge disconnected!", edgeId, sessionId); EdgeGrpcSession current = sessions.get(edgeId); - if (current != null && current.getSessionId().equals(sessionId)) { - EdgeGrpcSession toRemove = sessions.remove(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 { @@ -545,7 +558,13 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i destroySession(toRemove); sessionsById.remove(sessionId); TenantId tenantId = toRemove.getEdge().getTenantId(); - save(tenantId, edgeId, ACTIVITY_STATE, false); + // A newer session on another node may have already claimed this edge and set active=true. + // Clearing the flag here would leave the edge marked inactive while it is in fact connected, + // which silently drops every downlink event that is not queued for offline edges. + // When ownership is unknown (no cache entry) fall through and persist the inactive state. + if (!isOwnedByAnotherNode(edgeId)) { + save(tenantId, edgeId, ACTIVITY_STATE, false); + } long lastDisconnectTs = System.currentTimeMillis(); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); @@ -564,7 +583,37 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - edgeIdServiceIdCache.evict(edgeId); + // Only evict if the cache still points at this node. If the edge already reconnected to another + // TB-Core node, that node has overwritten the entry and owns it - evicting here would wipe the live + // owner's claim and defeat the activity-state guard above. + if (isOwnedByThisNode(edgeId)) { + edgeIdServiceIdCache.evict(edgeId); + } + } + + // The edge's service-id cache entry points at a different node that is still a live TB-Core service. + // Two cases deliberately do NOT count as "owned by another node", so that the caller falls through and + // persists the inactive state: + // - no cache entry: ownership is unknown, not claimed by someone else; + // - 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. + private boolean isOwnedByAnotherNode(EdgeId edgeId) { + TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); + if (wrapper == null) { + return false; + } + String ownerServiceId = wrapper.get(); + if (ownerServiceId == null || serviceInfoProvider.getServiceId().equals(ownerServiceId)) { + return false; + } + return partitionService.getAllServiceIds(ServiceType.TB_CORE).contains(ownerServiceId); + } + + // The edge's service-id cache entry still points at this node, i.e. this node is the recorded owner. + private boolean isOwnedByThisNode(EdgeId edgeId) { + TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); + return wrapper != null && serviceInfoProvider.getServiceId().equals(wrapper.get()); } private void destroySession(EdgeGrpcSession session) { 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 new file mode 100644 index 0000000000..7b71c65c9f --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -0,0 +1,221 @@ +/** + * 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; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatcher; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.rule.engine.api.AttributesSaveRequest; +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.queue.ServiceType; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; + +@ExtendWith(MockitoExtension.class) +public class EdgeGrpcServiceTest { + + private static final String THIS_NODE = "tb-core-1"; + private static final String OTHER_NODE = "tb-core-2"; + + @Mock + private TbTransactionalCache edgeIdServiceIdCache; + + @Mock + private TbServiceInfoProvider serviceInfoProvider; + + @Mock + private PartitionService partitionService; + + @Mock + private TelemetrySubscriptionService tsSubService; + + @Mock + private TbClusterService clusterService; + + @Mock + private EdgeContextComponent ctx; + + @InjectMocks + private EdgeGrpcService edgeGrpcService; + + private EdgeId edgeId; + private Edge edge; + + @BeforeEach + public void setUp() { + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + edge.setName("test-edge"); + } + + // --- activity-state write guard on disconnect --- + + @Test + public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenInactiveStateNotPersisted() { + // A newer session on another node already set active=true. This stale session's disconnect must not + // clobber it - otherwise the edge stays marked inactive while connected, and the server silently + // drops every assignment event for it. + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + 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(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); + } + + @Test + public void givenEdgeOwnedByThisNode_whenDisconnect_thenInactiveStateIsPersisted() { + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + + onEdgeDisconnect(sessionId); + + verify(tsSubService, times(1)).saveAttributes(argThat(inactiveStateWrite())); + } + + @Test + public void givenNoCacheEntry_whenDisconnect_thenInactiveStateIsPersisted() { + // Ownership unknown (entry absent or expired): keep the pre-guard behaviour, otherwise a genuinely + // disconnected edge would stay marked active forever. + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); + + onEdgeDisconnect(sessionId); + + verify(tsSubService, times(1)).saveAttributes(argThat(inactiveStateWrite())); + } + + @Test + public void givenOwnerNodeNoLongerInCluster_whenDisconnect_thenInactiveStateIsPersisted() { + // The recorded owner died without evicting its claim. The edge sessions cache has no TTL by default + // and only the owner ever evicts, so honouring a dead claim would leave the edge active forever. + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + 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)); + + onEdgeDisconnect(sessionId); + + verify(tsSubService, times(1)).saveAttributes(argThat(inactiveStateWrite())); + } + + @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. + 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); + + onEdgeDisconnect(staleSessionId); + + assertThat(sessions().get(edgeId)).isSameAs(live); + verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); + } + + // --- service-id cache eviction guard --- + + @Test + public void givenCacheOwnedByThisNode_whenDisconnect_thenEntryIsEvicted() { + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + + onEdgeDisconnect(sessionId); + + verify(edgeIdServiceIdCache, times(1)).evict(edgeId); + } + + @Test + public void givenCacheOwnedByAnotherNode_whenDisconnect_thenEntryIsKept() { + // The edge already reconnected elsewhere: wiping the live owner's claim would defeat the + // activity-state guard for any later disconnect callback. + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + 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(edgeIdServiceIdCache, never()).evict(edgeId); + } + + private void onEdgeDisconnect(UUID sessionId) { + ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId); + } + + private EdgeGrpcSession sessionFor(UUID sessionId) { + EdgeGrpcSession session = mock(EdgeGrpcSession.class); + when(session.getSessionId()).thenReturn(sessionId); + when(session.getEdge()).thenReturn(edge); + return session; + } + + @SuppressWarnings("unchecked") + private ConcurrentMap sessions() { + return (ConcurrentMap) ReflectionTestUtils.getField(edgeGrpcService, "sessions"); + } + + private ArgumentMatcher inactiveStateWrite() { + return request -> request != null + && edgeId.equals(request.getEntityId()) + && request.getEntries().stream().anyMatch(entry -> + ACTIVITY_STATE.equals(entry.getKey()) + && Boolean.FALSE.equals(entry.getBooleanValue().orElse(null))); + } + +}