Search in sources :

Example 1 with ApiUsageState

use of org.thingsboard.server.common.data.ApiUsageState in project thingsboard by thingsboard.

the class DefaultTbApiUsageStateServiceTest method givenTenantIdFromEntityStatesMap_whenGetApiUsageState.

@Test
public void givenTenantIdFromEntityStatesMap_whenGetApiUsageState() {
    service.myUsageStates.put(tenantId, tenantUsageStateMock);
    ApiUsageState tenantUsageState = service.getApiUsageState(tenantId);
    assertThat(tenantUsageState, is(tenantUsageStateMock.getApiUsageState()));
    Mockito.verify(service, never()).getOrFetchState(tenantId, tenantId);
}
Also used : ApiUsageState(org.thingsboard.server.common.data.ApiUsageState) Test(org.junit.Test)

Example 2 with ApiUsageState

use of org.thingsboard.server.common.data.ApiUsageState in project thingsboard by thingsboard.

the class DefaultTransportApiService method handle.

private ListenableFuture<TransportApiResponseMsg> handle(GetEntityProfileRequestMsg requestMsg) {
    EntityType entityType = EntityType.valueOf(requestMsg.getEntityType());
    UUID entityUuid = new UUID(requestMsg.getEntityIdMSB(), requestMsg.getEntityIdLSB());
    GetEntityProfileResponseMsg.Builder builder = GetEntityProfileResponseMsg.newBuilder();
    if (entityType.equals(EntityType.DEVICE_PROFILE)) {
        DeviceProfileId deviceProfileId = new DeviceProfileId(entityUuid);
        DeviceProfile deviceProfile = deviceProfileCache.find(deviceProfileId);
        builder.setData(ByteString.copyFrom(dataDecodingEncodingService.encode(deviceProfile)));
    } else if (entityType.equals(EntityType.TENANT)) {
        TenantId tenantId = TenantId.fromUUID(entityUuid);
        TenantProfile tenantProfile = tenantProfileCache.get(tenantId);
        ApiUsageState state = apiUsageStateService.getApiUsageState(tenantId);
        builder.setData(ByteString.copyFrom(dataDecodingEncodingService.encode(tenantProfile)));
        builder.setApiState(ByteString.copyFrom(dataDecodingEncodingService.encode(state)));
    } else {
        throw new RuntimeException("Invalid entity profile request: " + entityType);
    }
    return Futures.immediateFuture(TransportApiResponseMsg.newBuilder().setEntityProfileResponseMsg(builder).build());
}
Also used : EntityType(org.thingsboard.server.common.data.EntityType) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) TenantId(org.thingsboard.server.common.data.id.TenantId) DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) ApiUsageState(org.thingsboard.server.common.data.ApiUsageState) TenantProfile(org.thingsboard.server.common.data.TenantProfile) UUID(java.util.UUID) GetEntityProfileResponseMsg(org.thingsboard.server.gen.transport.TransportProtos.GetEntityProfileResponseMsg)

Example 3 with ApiUsageState

use of org.thingsboard.server.common.data.ApiUsageState in project thingsboard by thingsboard.

the class DefaultTbApiUsageStateService method getOrFetchState.

BaseApiUsageState getOrFetchState(TenantId tenantId, EntityId entityId) {
    if (entityId == null || entityId.isNullUid()) {
        entityId = tenantId;
    }
    BaseApiUsageState state = myUsageStates.get(entityId);
    if (state != null) {
        return state;
    }
    ApiUsageState storedState = apiUsageStateService.findApiUsageStateByEntityId(entityId);
    if (storedState == null) {
        try {
            storedState = apiUsageStateService.createDefaultApiUsageState(tenantId, entityId);
        } catch (Exception e) {
            storedState = apiUsageStateService.findApiUsageStateByEntityId(entityId);
        }
    }
    if (entityId.getEntityType() == EntityType.TENANT) {
        if (!entityId.equals(TenantId.SYS_TENANT_ID)) {
            state = new TenantApiUsageState(tenantProfileCache.get((TenantId) entityId), storedState);
        } else {
            state = new TenantApiUsageState(storedState);
        }
    } else {
        state = new CustomerApiUsageState(storedState);
    }
    List<ApiUsageRecordKey> newCounts = new ArrayList<>();
    try {
        List<TsKvEntry> dbValues = tsService.findAllLatest(tenantId, storedState.getId()).get();
        for (ApiUsageRecordKey key : ApiUsageRecordKey.values()) {
            boolean cycleEntryFound = false;
            boolean hourlyEntryFound = false;
            for (TsKvEntry tsKvEntry : dbValues) {
                if (tsKvEntry.getKey().equals(key.getApiCountKey())) {
                    cycleEntryFound = true;
                    boolean oldCount = tsKvEntry.getTs() == state.getCurrentCycleTs();
                    state.put(key, oldCount ? tsKvEntry.getLongValue().get() : 0L);
                    if (!oldCount) {
                        newCounts.add(key);
                    }
                } else if (tsKvEntry.getKey().equals(key.getApiCountKey() + HOURLY)) {
                    hourlyEntryFound = true;
                    state.putHourly(key, tsKvEntry.getTs() == state.getCurrentHourTs() ? tsKvEntry.getLongValue().get() : 0L);
                }
                if (cycleEntryFound && hourlyEntryFound) {
                    break;
                }
            }
        }
        log.debug("[{}] Initialized state: {}", entityId, storedState);
        TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, entityId);
        if (tpi.isMyPartition()) {
            addEntityState(tpi, state);
        } else {
            otherUsageStates.put(entityId, state.getApiUsageState());
        }
        saveNewCounts(state, newCounts);
    } catch (InterruptedException | ExecutionException e) {
        log.warn("[{}] Failed to fetch api usage state from db.", tenantId, e);
    }
    return state;
}
Also used : BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) ArrayList(java.util.ArrayList) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ExecutionException(java.util.concurrent.ExecutionException) ApiUsageRecordKey(org.thingsboard.server.common.data.ApiUsageRecordKey) TopicPartitionInfo(org.thingsboard.server.common.msg.queue.TopicPartitionInfo) ApiUsageState(org.thingsboard.server.common.data.ApiUsageState) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with ApiUsageState

use of org.thingsboard.server.common.data.ApiUsageState in project thingsboard by thingsboard.

the class TenantActor method onComponentLifecycleMsg.

private void onComponentLifecycleMsg(ComponentLifecycleMsg msg) {
    if (msg.getEntityId().getEntityType().equals(EntityType.API_USAGE_STATE)) {
        ApiUsageState old = getApiUsageState();
        apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId));
        if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) {
            log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId);
            destroyRuleChains();
        } else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled()) {
            log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId);
            initRuleChains();
        }
    } else if (msg.getEntityId().getEntityType() == EntityType.EDGE) {
        EdgeId edgeId = new EdgeId(msg.getEntityId().getId());
        EdgeRpcService edgeRpcService = systemContext.getEdgeRpcService();
        if (msg.getEvent() == ComponentLifecycleEvent.DELETED) {
            edgeRpcService.deleteEdge(tenantId, edgeId);
        } else {
            Edge edge = systemContext.getEdgeService().findEdgeById(tenantId, edgeId);
            if (msg.getEvent() == ComponentLifecycleEvent.UPDATED) {
                edgeRpcService.updateEdge(tenantId, edge);
            }
        }
    } else if (isRuleEngine) {
        TbActorRef target = getEntityActorRef(msg.getEntityId());
        if (target != null) {
            if (msg.getEntityId().getEntityType() == EntityType.RULE_CHAIN) {
                RuleChain ruleChain = systemContext.getRuleChainService().findRuleChainById(tenantId, new RuleChainId(msg.getEntityId().getId()));
                if (ruleChain != null && RuleChainType.CORE.equals(ruleChain.getType())) {
                    visit(ruleChain, target);
                }
            }
            target.tellWithHighPriority(msg);
        } else {
            log.debug("[{}] Invalid component lifecycle msg: {}", tenantId, msg);
        }
    }
}
Also used : ApiUsageState(org.thingsboard.server.common.data.ApiUsageState) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) EdgeId(org.thingsboard.server.common.data.id.EdgeId) TbActorRef(org.thingsboard.server.actors.TbActorRef) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) EdgeRpcService(org.thingsboard.server.service.edge.rpc.EdgeRpcService) Edge(org.thingsboard.server.common.data.edge.Edge)

Example 5 with ApiUsageState

use of org.thingsboard.server.common.data.ApiUsageState in project thingsboard by thingsboard.

the class ApiUsageStateEntity method toData.

@Override
public ApiUsageState toData() {
    ApiUsageState ur = new ApiUsageState(new ApiUsageStateId(this.getUuid()));
    ur.setCreatedTime(createdTime);
    if (tenantId != null) {
        ur.setTenantId(TenantId.fromUUID(tenantId));
    }
    if (entityId != null) {
        ur.setEntityId(EntityIdFactory.getByTypeAndUuid(entityType, entityId));
    }
    ur.setTransportState(transportState);
    ur.setDbStorageState(dbStorageState);
    ur.setReExecState(reExecState);
    ur.setJsExecState(jsExecState);
    ur.setEmailExecState(emailExecState);
    ur.setSmsExecState(smsExecState);
    ur.setAlarmExecState(alarmExecState);
    return ur;
}
Also used : ApiUsageState(org.thingsboard.server.common.data.ApiUsageState) ApiUsageStateId(org.thingsboard.server.common.data.id.ApiUsageStateId)

Aggregations

ApiUsageState (org.thingsboard.server.common.data.ApiUsageState)10 Test (org.junit.Test)3 ApiUsageRecordKey (org.thingsboard.server.common.data.ApiUsageRecordKey)3 EntityType (org.thingsboard.server.common.data.EntityType)3 TenantProfile (org.thingsboard.server.common.data.TenantProfile)3 TenantId (org.thingsboard.server.common.data.id.TenantId)3 ByteString (com.google.protobuf.ByteString)2 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2 Set (java.util.Set)2 UUID (java.util.UUID)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 ExecutionException (java.util.concurrent.ExecutionException)2 Slf4j (lombok.extern.slf4j.Slf4j)2 Tenant (org.thingsboard.server.common.data.Tenant)2 RuleChainId (org.thingsboard.server.common.data.id.RuleChainId)2 TenantProfileId (org.thingsboard.server.common.data.id.TenantProfileId)2 BasicTsKvEntry (org.thingsboard.server.common.data.kv.BasicTsKvEntry)2