Browse Source
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.pull/16156/head
2 changed files with 275 additions and 5 deletions
@ -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<EdgeId, String> 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<EdgeId, EdgeGrpcSession> sessions() { |
|||
return (ConcurrentMap<EdgeId, EdgeGrpcSession>) ReflectionTestUtils.getField(edgeGrpcService, "sessions"); |
|||
} |
|||
|
|||
private ArgumentMatcher<AttributesSaveRequest> 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))); |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue