Search in sources :

Example 21 with TopicPartitionInfo

use of org.thingsboard.server.common.msg.queue.TopicPartitionInfo in project thingsboard by thingsboard.

the class DeviceProvisionServiceImpl method sendToRuleEngine.

protected void sendToRuleEngine(TenantId tenantId, TbMsg tbMsg, TbQueueCallback callback) {
    TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_RULE_ENGINE, tenantId, tbMsg.getOriginator());
    TransportProtos.ToRuleEngineMsg msg = TransportProtos.ToRuleEngineMsg.newBuilder().setTbMsg(TbMsg.toByteString(tbMsg)).setTenantIdMSB(tenantId.getId().getMostSignificantBits()).setTenantIdLSB(tenantId.getId().getLeastSignificantBits()).build();
    ruleEngineMsgProducer.send(tpi, new TbProtoQueueMsg<>(tbMsg.getId(), msg), callback);
}
Also used : TopicPartitionInfo(org.thingsboard.server.common.msg.queue.TopicPartitionInfo) ToRuleEngineMsg(org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg) TransportProtos(org.thingsboard.server.gen.transport.TransportProtos)

Example 22 with TopicPartitionInfo

use of org.thingsboard.server.common.msg.queue.TopicPartitionInfo in project thingsboard by thingsboard.

the class HashPartitionServiceTest method testDevicesDispersion.

private void testDevicesDispersion(List<DeviceId> devices) {
    long start = System.currentTimeMillis();
    Map<Integer, Integer> map = new HashMap<>();
    for (DeviceId deviceId : devices) {
        TopicPartitionInfo address = clusterRoutingService.resolve(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID, deviceId);
        Integer partition = address.getPartition().get();
        map.put(partition, map.getOrDefault(partition, 0) + 1);
    }
    List<Map.Entry<Integer, Integer>> data = map.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getValue)).collect(Collectors.toList());
    long end = System.currentTimeMillis();
    double diff = (data.get(data.size() - 1).getValue() - data.get(0).getValue());
    double diffPercent = (diff / ITERATIONS) * 100.0;
    System.out.println("Time: " + (end - start) + " Diff: " + diff + "(" + String.format("%f", diffPercent) + "%)");
    Assert.assertTrue(diffPercent < 0.5);
    for (Map.Entry<Integer, Integer> entry : data) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}
Also used : TopicPartitionInfo(org.thingsboard.server.common.msg.queue.TopicPartitionInfo) HashMap(java.util.HashMap) DeviceId(org.thingsboard.server.common.data.id.DeviceId) HashMap(java.util.HashMap) Map(java.util.Map)

Example 23 with TopicPartitionInfo

use of org.thingsboard.server.common.msg.queue.TopicPartitionInfo in project thingsboard by thingsboard.

the class DefaultTransportService method init.

@PostConstruct
public void init() {
    this.ruleEngineProducerStats = statsFactory.createMessagesStats(StatsType.RULE_ENGINE.getName() + ".producer");
    this.tbCoreProducerStats = statsFactory.createMessagesStats(StatsType.CORE.getName() + ".producer");
    this.transportApiStats = statsFactory.createMessagesStats(StatsType.TRANSPORT.getName() + ".producer");
    this.transportCallbackExecutor = ThingsBoardExecutors.newWorkStealingPool(20, getClass());
    this.scheduler.scheduleAtFixedRate(this::checkInactivityAndReportActivity, new Random().nextInt((int) sessionReportTimeout), sessionReportTimeout, TimeUnit.MILLISECONDS);
    this.scheduler.scheduleAtFixedRate(this::invalidateRateLimits, new Random().nextInt((int) sessionReportTimeout), sessionReportTimeout, TimeUnit.MILLISECONDS);
    transportApiRequestTemplate = queueProvider.createTransportApiRequestTemplate();
    transportApiRequestTemplate.setMessagesStats(transportApiStats);
    ruleEngineMsgProducer = producerProvider.getRuleEngineMsgProducer();
    tbCoreMsgProducer = producerProvider.getTbCoreMsgProducer();
    transportNotificationsConsumer = queueProvider.createTransportNotificationsConsumer();
    TopicPartitionInfo tpi = partitionService.getNotificationsTopic(ServiceType.TB_TRANSPORT, serviceInfoProvider.getServiceId());
    transportNotificationsConsumer.subscribe(Collections.singleton(tpi));
    transportApiRequestTemplate.init();
    mainConsumerExecutor = Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName("transport-consumer"));
}
Also used : Random(java.util.Random) TopicPartitionInfo(org.thingsboard.server.common.msg.queue.TopicPartitionInfo) PostConstruct(javax.annotation.PostConstruct)

Example 24 with TopicPartitionInfo

use of org.thingsboard.server.common.msg.queue.TopicPartitionInfo in project thingsboard by thingsboard.

the class DefaultTransportService method sendToDeviceActor.

protected void sendToDeviceActor(TransportProtos.SessionInfoProto sessionInfo, TransportToDeviceActorMsg toDeviceActorMsg, TransportServiceCallback<Void> callback) {
    TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, getTenantId(sessionInfo), getDeviceId(sessionInfo));
    if (log.isTraceEnabled()) {
        log.trace("[{}][{}] Pushing to topic {} message {}", getTenantId(sessionInfo), getDeviceId(sessionInfo), tpi.getFullTopicName(), toDeviceActorMsg);
    }
    TransportTbQueueCallback transportTbQueueCallback = callback != null ? new TransportTbQueueCallback(callback) : null;
    tbCoreProducerStats.incrementTotal();
    StatsCallback wrappedCallback = new StatsCallback(transportTbQueueCallback, tbCoreProducerStats);
    tbCoreMsgProducer.send(tpi, new TbProtoQueueMsg<>(getRoutingKey(sessionInfo), ToCoreMsg.newBuilder().setToDeviceActorMsg(toDeviceActorMsg).build()), wrappedCallback);
}
Also used : TopicPartitionInfo(org.thingsboard.server.common.msg.queue.TopicPartitionInfo)

Example 25 with TopicPartitionInfo

use of org.thingsboard.server.common.msg.queue.TopicPartitionInfo in project thingsboard by thingsboard.

the class DefaultTbApiUsageStateService method onAddedPartitions.

@Override
protected void onAddedPartitions(Set<TopicPartitionInfo> addedPartitions) {
    try {
        log.info("Initializing tenant states.");
        updateLock.lock();
        try {
            PageDataIterable<Tenant> tenantIterator = new PageDataIterable<>(tenantService::findTenants, 1024);
            List<ListenableFuture<?>> futures = new ArrayList<>();
            for (Tenant tenant : tenantIterator) {
                TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenant.getId(), tenant.getId());
                if (addedPartitions.contains(tpi)) {
                    if (!myUsageStates.containsKey(tenant.getId()) && tpi.isMyPartition()) {
                        log.debug("[{}] Initializing tenant state.", tenant.getId());
                        futures.add(dbExecutor.submit(() -> {
                            try {
                                updateTenantState((TenantApiUsageState) getOrFetchState(tenant.getId(), tenant.getId()), tenantProfileCache.get(tenant.getTenantProfileId()));
                                log.debug("[{}] Initialized tenant state.", tenant.getId());
                            } catch (Exception e) {
                                log.warn("[{}] Failed to initialize tenant API state", tenant.getId(), e);
                            }
                            return null;
                        }));
                    }
                } else {
                    log.debug("[{}][{}] Tenant doesn't belong to current partition. tpi [{}]", tenant.getName(), tenant.getId(), tpi);
                }
            }
            Futures.whenAllComplete(futures);
        } finally {
            updateLock.unlock();
        }
        log.info("Initialized {} tenant states.", myUsageStates.size());
    } catch (Exception e) {
        log.warn("Unknown failure", e);
    }
}
Also used : PageDataIterable(org.thingsboard.server.common.data.page.PageDataIterable) Tenant(org.thingsboard.server.common.data.Tenant) TopicPartitionInfo(org.thingsboard.server.common.msg.queue.TopicPartitionInfo) ArrayList(java.util.ArrayList) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

TopicPartitionInfo (org.thingsboard.server.common.msg.queue.TopicPartitionInfo)50 ArrayList (java.util.ArrayList)10 TransportProtos (org.thingsboard.server.gen.transport.TransportProtos)10 TenantId (org.thingsboard.server.common.data.id.TenantId)7 TbProtoQueueMsg (org.thingsboard.server.queue.common.TbProtoQueueMsg)7 EntityId (org.thingsboard.server.common.data.id.EntityId)6 TsKvEntry (org.thingsboard.server.common.data.kv.TsKvEntry)6 UUID (java.util.UUID)5 BasicTsKvEntry (org.thingsboard.server.common.data.kv.BasicTsKvEntry)5 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Set (java.util.Set)4 PostConstruct (javax.annotation.PostConstruct)4 Slf4j (lombok.extern.slf4j.Slf4j)4 EntityType (org.thingsboard.server.common.data.EntityType)4 DeviceId (org.thingsboard.server.common.data.id.DeviceId)4 ServiceType (org.thingsboard.server.common.msg.queue.ServiceType)4 ToCoreNotificationMsg (org.thingsboard.server.gen.transport.TransportProtos.ToCoreNotificationMsg)4 ToRuleEngineMsg (org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg)4 ByteString (com.google.protobuf.ByteString)3