Browse Source

Merge pull request #15729 from smatvienko-tb/fix/skip-notification-to-unknown-service-id

Fixed unbounded growth of Kafka notification topics from RPC and REST API reply flows
pull/16363/head
Viacheslav Klimov 1 month ago
committed by GitHub
parent
commit
ee00fe9c5b
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 111
      application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
  2. 9
      application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java
  3. 205
      application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java
  4. 19
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java
  5. 6
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java
  6. 16
      common/util/src/main/java/org/thingsboard/common/util/SetCache.java

111
application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java

@ -7,9 +7,11 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.SetCache;
import org.thingsboard.server.cache.TbTransactionalCache;
import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.data.ApiUsageState;
@ -83,6 +85,7 @@ import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.common.TbRuleEngineProducerService;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TopicService;
import org.thingsboard.server.queue.discovery.event.ServiceListChangedEvent;
import org.thingsboard.server.queue.provider.TbQueueProducerProvider;
import org.thingsboard.server.service.gateway_device.GatewayNotificationsService;
import org.thingsboard.server.service.ota.OtaPackageStateService;
@ -116,6 +119,12 @@ public class DefaultTbClusterService implements TbClusterService {
private final AtomicInteger toTransportNfs = new AtomicInteger(0);
private final AtomicInteger toEdgeMsgs = new AtomicInteger(0);
private final AtomicInteger toEdgeNfs = new AtomicInteger(0);
private final AtomicInteger skippedUnknownServiceNfs = new AtomicInteger(0);
private static final int RECENTLY_SEEN_SERVICES_MAX_SIZE = 1024;
// serviceType:serviceId -> seen. Bounded LRU of cluster members ever observed, used to grace a service id that is
// briefly missing from the live snapshot (see isUnknownService). Fed from ServiceListChangedEvent.
private final SetCache<String> recentlySeenServices = SetCache.boundedBySize(RECENTLY_SEEN_SERVICES_MAX_SIZE);
@Autowired
private PartitionService partitionService;
@ -195,6 +204,10 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToCore(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) {
if (isUnknownService(ServiceType.TB_CORE, serviceId)) {
skipNotificationToUnknownService(ServiceType.TB_CORE, serviceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, serviceId);
log.trace("PUSHING msg: {} to:{}", response, tpi);
FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder()
@ -209,12 +222,93 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToCore(String targetServiceId, TransportProtos.RestApiCallResponseMsgProto responseMsgProto, TbQueueCallback callback) {
if (isUnknownService(ServiceType.TB_CORE, targetServiceId)) {
skipNotificationToUnknownService(ServiceType.TB_CORE, targetServiceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, targetServiceId);
ToCoreNotificationMsg msg = ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build();
producerProvider.getTbCoreNotificationsMsgProducer().send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), msg), callback);
toCoreNfs.incrementAndGet();
}
/**
* Per-service notification topics ({@code <notifications-topic>.<serviceId>}) are auto-created by the producer on
* first send. A {@code serviceId} that is not a member of the cluster - e.g. a stale node id or a value injected
* via message metadata - would therefore create an orphan topic that nobody ever consumes and that is never
* cleaned up. To prevent that, notifications whose target service id is not a current member of the cluster are
* skipped.
* <p>
* This is a safety net for never-real ids, not a precise gatekeeper, so it is deliberately lenient. A service id is
* treated as known if it is either a current member ({@link PartitionService#isKnownServiceId}) or a recently seen
* one ({@link #recentlySeenServices}). The recently-seen grace covers nodes that are briefly absent from the live
* snapshot - a discovery-propagation lag, a rolling restart or a transient scale-down - so legitimate replies to
* them are not dropped; genuine non-delivery to a node that is actually gone is already handled by the caller-side
* RPC/REST timeout. The check also fails open while the cluster topology is not yet known (empty/absent membership,
* e.g. right after startup).
*/
private boolean isUnknownService(ServiceType serviceType, String serviceId) {
if (serviceId == null || serviceId.isEmpty()) {
return true;
}
if (partitionService.isKnownServiceId(serviceType, serviceId)) {
return false; // currently a live member
}
Set<String> serviceIds = partitionService.getAllServiceIds(serviceType);
if (serviceIds == null || serviceIds.isEmpty()) {
return false; // topology not known yet - fail open
}
return !recentlySeenServices.contains(recentlySeenServiceKey(serviceType, serviceId));
}
private void skipNotificationToUnknownService(ServiceType serviceType, String serviceId, TbQueueCallback callback) {
log.debug("Skipping notification push to unknown {} service id [{}]", serviceType, serviceId);
skippedUnknownServiceNfs.incrementAndGet();
if (callback != null) {
// Deliberate skip - the target is not a cluster member. Complete the callback as a no-op success,
// matching pushNotificationToTransport, so callers don't treat an intentional skip as a delivery error.
callback.onSuccess(null);
}
}
/**
* Records every observed cluster member so that {@link #isUnknownService} can grace a service id that has dropped
* out of the live snapshot (propagation lag, rolling restart, transient scale-down) instead of dropping
* notifications to it. Bounded by {@link #RECENTLY_SEEN_SERVICES_MAX_SIZE} with LRU eviction, so an id that is gone
* for good eventually ages out and the guard tightens again. Discovery events are change-only, so this never
* removes entries - it only adds; the live-snapshot check in {@link #isUnknownService} stays authoritative for
* current members.
*/
@EventListener
public void onServiceListChanged(ServiceListChangedEvent event) {
rememberSeenService(event.getCurrentService());
List<TransportProtos.ServiceInfo> otherServices = event.getOtherServices();
if (otherServices != null) {
otherServices.forEach(this::rememberSeenService);
}
}
private void rememberSeenService(TransportProtos.ServiceInfo serviceInfo) {
if (serviceInfo == null) {
return;
}
String serviceId = serviceInfo.getServiceId();
if (serviceId == null || serviceId.isEmpty()) {
return;
}
for (String serviceType : serviceInfo.getServiceTypesList()) {
recentlySeenServices.add(recentlySeenServiceKey(serviceType, serviceId));
}
}
private static String recentlySeenServiceKey(ServiceType serviceType, String serviceId) {
return recentlySeenServiceKey(serviceType.name(), serviceId);
}
private static String recentlySeenServiceKey(String serviceType, String serviceId) {
return serviceType + ":" + serviceId;
}
@Override
public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) {
log.trace("PUSHING msg: {} to:{}", msg, tpi);
@ -309,6 +403,10 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToRuleEngine(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) {
if (isUnknownService(ServiceType.TB_RULE_ENGINE, serviceId)) {
skipNotificationToUnknownService(ServiceType.TB_RULE_ENGINE, serviceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_RULE_ENGINE, serviceId);
log.trace("PUSHING msg: {} to:{}", response, tpi);
FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder()
@ -323,11 +421,8 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToTransport(String serviceId, ToTransportMsg response, TbQueueCallback callback) {
if (serviceId == null || serviceId.isEmpty()) {
log.trace("pushNotificationToTransport: skipping message without serviceId [{}], (ToTransportMsg) response [{}]", serviceId, response);
if (callback != null) {
callback.onSuccess(null); //callback that message already sent, no useful payload expected
}
if (isUnknownService(ServiceType.TB_TRANSPORT, serviceId)) {
skipNotificationToUnknownService(ServiceType.TB_TRANSPORT, serviceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_TRANSPORT, serviceId);
@ -617,9 +712,11 @@ public class DefaultTbClusterService implements TbClusterService {
int toTransportNfsCnt = toTransportNfs.getAndSet(0);
int toEdgeMsgCnt = toEdgeMsgs.getAndSet(0);
int toEdgeNfsCnt = toEdgeNfs.getAndSet(0);
if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0) {
int skippedUnknownServiceNfsCnt = skippedUnknownServiceNfs.getAndSet(0);
if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0 || skippedUnknownServiceNfsCnt > 0) {
log.info("To TbCore: [{}] messages [{}] notifications; To TbRuleEngine: [{}] messages [{}] notifications; To Transport: [{}] notifications;" +
"To Edge: [{}] messages [{}] notifications", toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt);
"To Edge: [{}] messages [{}] notifications; Skipped notifications to unknown service id: [{}]",
toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt, skippedUnknownServiceNfsCnt);
}
}
}

9
application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java

@ -83,6 +83,7 @@ public class HashPartitionServiceTest {
.setServiceId("tb-core-0")
.addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name()))
.build();
when(serviceInfoProvider.getServiceInfo()).thenReturn(currentServer);
List<ServiceInfo> otherServers = new ArrayList<>();
for (int i = 1; i < SERVER_COUNT; i++) {
otherServers.add(ServiceInfo.newBuilder()
@ -94,6 +95,14 @@ public class HashPartitionServiceTest {
partitionService.recalculatePartitions(currentServer, otherServers);
}
@Test
public void testIsKnownServiceId() {
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-core-0")).isTrue(); // current server
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-rule-1")).isTrue(); // other server
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "unknown-id")).isFalse();
assertThat(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, "tb-core-0")).isFalse(); // wrong type
}
@Test
public void testDispersionOnMillionDevices() {
List<DeviceId> devices = new ArrayList<>();

205
application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java

@ -32,6 +32,7 @@ import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.common.msg.queue.TopicPartitionInfo;
import org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.edge.EdgeService;
import org.thingsboard.server.gen.transport.TransportProtos;
@ -42,6 +43,7 @@ import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.common.TbRuleEngineProducerService;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TopicService;
import org.thingsboard.server.queue.discovery.event.ServiceListChangedEvent;
import org.thingsboard.server.queue.provider.TbQueueProducerProvider;
import org.thingsboard.server.service.gateway_device.GatewayNotificationsService;
import org.thingsboard.server.service.ota.OtaPackageStateService;
@ -77,6 +79,8 @@ public class DefaultTbClusterServiceTest {
public static final String TRANSPORT = "transport";
public static final String UNKNOWN_SERVICE_ID = "not-a-cluster-member";
@MockitoBean
protected TbDeviceProfileCache deviceProfileCache;
@MockitoBean
@ -277,6 +281,7 @@ public class DefaultTbClusterServiceTest {
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
TransportProtos.RestApiCallResponseMsgProto responseMsgProto = TransportProtos.RestApiCallResponseMsgProto.getDefaultInstance();
TransportProtos.ToCoreNotificationMsg toCoreNotificationMsg = TransportProtos.ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build();
@ -291,6 +296,206 @@ public class DefaultTbClusterServiceTest {
assertThat(protoQueueMsgArgumentCaptorValue.getKey()).isNotNull();
assertThat(protoQueueMsgArgumentCaptorValue.getValue()).isEqualTo(toCoreNotificationMsg);
assertThat(protoQueueMsgArgumentCaptorValue.getHeaders().getData()).isEqualTo(new DefaultTbQueueMsgHeaders().getData());
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE);
}
@Test
public void testPushNotificationToCoreToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_CORE), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getTbCoreNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToCoreToRecentlySeenButOfflineServiceIdIsSent() {
String offlineCore = "core-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
// offlineCore was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineCore).addServiceTypes(ServiceType.TB_CORE.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(CORE).addServiceTypes(ServiceType.TB_CORE.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, offlineCore);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(offlineCore, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToCoreToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, CORE);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(CORE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE);
}
@Test
public void testPushNotificationToCoreFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToRuleEngineToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_RULE_ENGINE), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getRuleEngineNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToRuleEngineToRecentlySeenButOfflineServiceIdIsSent() {
String offlineRuleEngine = "rule-engine-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
// offlineRuleEngine was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineRuleEngine).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(RULE_ENGINE).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, offlineRuleEngine);
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(offlineRuleEngine, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToRuleEngineToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, RULE_ENGINE)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, RULE_ENGINE);
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(RULE_ENGINE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_RULE_ENGINE);
}
@Test
public void testPushNotificationToRuleEngineFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToTransportToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_TRANSPORT), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getTransportNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToTransportToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_TRANSPORT, TRANSPORT)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, TRANSPORT);
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(TRANSPORT, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_TRANSPORT);
}
@Test
public void testPushNotificationToTransportToRecentlySeenButOfflineServiceIdIsSent() {
String offlineTransport = "transport-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
// offlineTransport was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineTransport).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(TRANSPORT).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, offlineTransport);
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(offlineTransport, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToTransportFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test

19
common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java

@ -96,7 +96,7 @@ public class HashPartitionService implements PartitionService {
private final ConcurrentMap<TenantId, TenantRoutingInfo> tenantRoutingInfoMap = new ConcurrentHashMap<>();
private List<ServiceInfo> currentOtherServices;
private volatile List<ServiceInfo> currentOtherServices;
private final Map<String, List<ServiceInfo>> tbTransportServicesByType = new HashMap<>();
private volatile Map<TenantProfileId, List<ServiceInfo>> responsibleServices = Collections.emptyMap();
@ -537,6 +537,23 @@ public class HashPartitionService implements PartitionService {
return getAllServices(serviceType).stream().map(ServiceInfo::getServiceId).collect(Collectors.toSet());
}
@Override
public boolean isKnownServiceId(ServiceType serviceType, String serviceId) {
ServiceInfo current = serviceInfoProvider.getServiceInfo();
if (serviceId.equals(current.getServiceId()) && current.getServiceTypesList().contains(serviceType.name())) {
return true;
}
List<ServiceInfo> others = currentOtherServices;
if (others != null) {
for (ServiceInfo serviceInfo : others) {
if (serviceId.equals(serviceInfo.getServiceId()) && serviceInfo.getServiceTypesList().contains(serviceType.name())) {
return true;
}
}
}
return false;
}
@Override
public Set<ServiceInfo> getAllServices(ServiceType serviceType) {
Set<ServiceInfo> result = getOtherServices(serviceType);

6
common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java

@ -48,6 +48,12 @@ public interface PartitionService {
*/
Set<String> getAllServiceIds(ServiceType serviceType);
/**
* Cheaper alternative to {@link #getAllServiceIds} when only membership of a single id needs to be checked -
* avoids building the full service id set.
*/
boolean isKnownServiceId(ServiceType serviceType, String serviceId);
Set<TransportProtos.ServiceInfo> getAllServices(ServiceType serviceType);
Set<TransportProtos.ServiceInfo> getOtherServices(ServiceType serviceType);

16
common/util/src/main/java/org/thingsboard/common/util/SetCache.java

@ -14,9 +14,19 @@ public class SetCache<K> {
private final Cache<K, Object> cache;
public SetCache(long valueTtlMs) {
this.cache = Caffeine.newBuilder()
.expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS)
.build();
this(Caffeine.newBuilder().expireAfterWrite(valueTtlMs, TimeUnit.MILLISECONDS));
}
private SetCache(Caffeine<Object, Object> builder) {
this.cache = builder.build();
}
/**
* Bounded by entry count with LRU-ish eviction, instead of a TTL - for callers that want to remember
* up to N recently seen keys rather than expire entries after a fixed duration.
*/
public static <T> SetCache<T> boundedBySize(int maximumSize) {
return new SetCache<>(Caffeine.newBuilder().maximumSize(maximumSize));
}
public void add(K key) {

Loading…
Cancel
Save