Search in sources :

Example 6 with RuleChain

use of org.thingsboard.server.common.data.rule.RuleChain in project thingsboard by thingsboard.

the class RuleChainActorMessageProcessor method onUpdate.

@Override
public void onUpdate(TbActorCtx context) {
    RuleChain ruleChain = service.findRuleChainById(tenantId, entityId);
    if (ruleChain != null && RuleChainType.CORE.equals(ruleChain.getType())) {
        ruleChainName = ruleChain.getName();
        List<RuleNode> ruleNodeList = service.getRuleChainNodes(tenantId, entityId);
        log.trace("[{}][{}] Updating rule chain with {} nodes", tenantId, entityId, ruleNodeList.size());
        for (RuleNode ruleNode : ruleNodeList) {
            RuleNodeCtx existing = nodeActors.get(ruleNode.getId());
            if (existing == null) {
                log.trace("[{}][{}] Creating rule node [{}]: {}", entityId, ruleNode.getId(), ruleNode.getName(), ruleNode);
                TbActorRef ruleNodeActor = createRuleNodeActor(context, ruleNode);
                nodeActors.put(ruleNode.getId(), new RuleNodeCtx(tenantId, self, ruleNodeActor, ruleNode));
            } else {
                log.trace("[{}][{}] Updating rule node [{}]: {}", entityId, ruleNode.getId(), ruleNode.getName(), ruleNode);
                existing.setSelf(ruleNode);
                existing.getSelfActor().tellWithHighPriority(new RuleNodeUpdatedMsg(tenantId, existing.getSelf().getId()));
            }
        }
        Set<RuleNodeId> existingNodes = ruleNodeList.stream().map(RuleNode::getId).collect(Collectors.toSet());
        List<RuleNodeId> removedRules = nodeActors.keySet().stream().filter(node -> !existingNodes.contains(node)).collect(Collectors.toList());
        removedRules.forEach(ruleNodeId -> {
            log.trace("[{}][{}] Removing rule node [{}]", tenantId, entityId, ruleNodeId);
            RuleNodeCtx removed = nodeActors.remove(ruleNodeId);
            removed.getSelfActor().tellWithHighPriority(new ComponentLifecycleMsg(tenantId, removed.getSelf().getId(), ComponentLifecycleEvent.DELETED));
        });
        initRoutes(ruleChain, ruleNodeList);
    }
}
Also used : TbMsg(org.thingsboard.server.common.msg.TbMsg) HashMap(java.util.HashMap) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId) ComponentMsgProcessor(org.thingsboard.server.actors.shared.ComponentMsgProcessor) TenantId(org.thingsboard.server.common.data.id.TenantId) RuleChainService(org.thingsboard.server.dao.rule.RuleChainService) DefaultActorService(org.thingsboard.server.actors.service.DefaultActorService) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) ArrayList(java.util.ArrayList) ComponentLifecycleState(org.thingsboard.server.common.data.plugin.ComponentLifecycleState) ActorSystemContext(org.thingsboard.server.actors.ActorSystemContext) ServiceType(org.thingsboard.server.common.msg.queue.ServiceType) QueueToRuleEngineMsg(org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg) Map(java.util.Map) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityType(org.thingsboard.server.common.data.EntityType) TbQueueTbMsgCallbackWrapper(org.thingsboard.server.queue.common.TbQueueTbMsgCallbackWrapper) RuleNodeUpdatedMsg(org.thingsboard.server.common.msg.plugin.RuleNodeUpdatedMsg) TbQueueCallback(org.thingsboard.server.queue.TbQueueCallback) TbApiUsageClient(org.thingsboard.server.queue.usagestats.TbApiUsageClient) TbEntityActorId(org.thingsboard.server.actors.TbEntityActorId) ComponentLifecycleMsg(org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg) RuleChainType(org.thingsboard.server.common.data.rule.RuleChainType) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) RuleNodeException(org.thingsboard.server.common.msg.queue.RuleNodeException) Set(java.util.Set) TbActorCtx(org.thingsboard.server.actors.TbActorCtx) TbRelationTypes(org.thingsboard.rule.engine.api.TbRelationTypes) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ComponentLifecycleEvent(org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent) PartitionChangeMsg(org.thingsboard.server.common.msg.queue.PartitionChangeMsg) RuleEngineException(org.thingsboard.server.common.msg.queue.RuleEngineException) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) ToRuleEngineMsg(org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) MultipleTbQueueTbMsgCallbackWrapper(org.thingsboard.server.queue.common.MultipleTbQueueTbMsgCallbackWrapper) TbClusterService(org.thingsboard.server.cluster.TbClusterService) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) Collections(java.util.Collections) TbActorRef(org.thingsboard.server.actors.TbActorRef) TopicPartitionInfo(org.thingsboard.server.common.msg.queue.TopicPartitionInfo) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) TbActorRef(org.thingsboard.server.actors.TbActorRef) RuleNodeUpdatedMsg(org.thingsboard.server.common.msg.plugin.RuleNodeUpdatedMsg) ComponentLifecycleMsg(org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId)

Example 7 with RuleChain

use of org.thingsboard.server.common.data.rule.RuleChain in project thingsboard by thingsboard.

the class DefaultDataUpdateService method updateNestedRuleChains.

private void updateNestedRuleChains() {
    try {
        var packSize = 1024;
        var updated = 0;
        boolean hasNext = true;
        while (hasNext) {
            List<EntityRelation> relations = relationService.findRuleNodeToRuleChainRelations(TenantId.SYS_TENANT_ID, RuleChainType.CORE, packSize);
            hasNext = relations.size() == packSize;
            for (EntityRelation relation : relations) {
                try {
                    RuleNodeId sourceNodeId = new RuleNodeId(relation.getFrom().getId());
                    RuleNode sourceNode = ruleChainService.findRuleNodeById(TenantId.SYS_TENANT_ID, sourceNodeId);
                    if (sourceNode == null) {
                        log.info("Skip processing of relation for non existing source rule node: [{}]", sourceNodeId);
                        relationService.deleteRelation(TenantId.SYS_TENANT_ID, relation);
                        continue;
                    }
                    RuleChainId sourceRuleChainId = sourceNode.getRuleChainId();
                    RuleChainId targetRuleChainId = new RuleChainId(relation.getTo().getId());
                    RuleChain targetRuleChain = ruleChainService.findRuleChainById(TenantId.SYS_TENANT_ID, targetRuleChainId);
                    if (targetRuleChain == null) {
                        log.info("Skip processing of relation for non existing target rule chain: [{}]", targetRuleChainId);
                        relationService.deleteRelation(TenantId.SYS_TENANT_ID, relation);
                        continue;
                    }
                    TenantId tenantId = targetRuleChain.getTenantId();
                    RuleNode targetNode = new RuleNode();
                    targetNode.setName(targetRuleChain.getName());
                    targetNode.setRuleChainId(sourceRuleChainId);
                    targetNode.setType(TbRuleChainInputNode.class.getName());
                    TbRuleChainInputNodeConfiguration configuration = new TbRuleChainInputNodeConfiguration();
                    configuration.setRuleChainId(targetRuleChain.getId().toString());
                    targetNode.setConfiguration(JacksonUtil.valueToTree(configuration));
                    targetNode.setAdditionalInfo(relation.getAdditionalInfo());
                    targetNode.setDebugMode(false);
                    targetNode = ruleChainService.saveRuleNode(tenantId, targetNode);
                    EntityRelation sourceRuleChainToRuleNode = new EntityRelation();
                    sourceRuleChainToRuleNode.setFrom(sourceRuleChainId);
                    sourceRuleChainToRuleNode.setTo(targetNode.getId());
                    sourceRuleChainToRuleNode.setType(EntityRelation.CONTAINS_TYPE);
                    sourceRuleChainToRuleNode.setTypeGroup(RelationTypeGroup.RULE_CHAIN);
                    relationService.saveRelation(tenantId, sourceRuleChainToRuleNode);
                    EntityRelation sourceRuleNodeToTargetRuleNode = new EntityRelation();
                    sourceRuleNodeToTargetRuleNode.setFrom(sourceNode.getId());
                    sourceRuleNodeToTargetRuleNode.setTo(targetNode.getId());
                    sourceRuleNodeToTargetRuleNode.setType(relation.getType());
                    sourceRuleNodeToTargetRuleNode.setTypeGroup(RelationTypeGroup.RULE_NODE);
                    sourceRuleNodeToTargetRuleNode.setAdditionalInfo(relation.getAdditionalInfo());
                    relationService.saveRelation(tenantId, sourceRuleNodeToTargetRuleNode);
                    // Delete old relation
                    relationService.deleteRelation(tenantId, relation);
                    updated++;
                } catch (Exception e) {
                    log.info("Failed to update RuleNodeToRuleChainRelation: {}", relation, e);
                }
            }
            if (updated > 0) {
                log.info("RuleNodeToRuleChainRelations: {} entities updated so far...", updated);
            }
        }
    } catch (Exception e) {
        log.error("Unable to update Tenant", e);
    }
}
Also used : EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) TenantId(org.thingsboard.server.common.data.id.TenantId) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) ExecutionException(java.util.concurrent.ExecutionException) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId) TbRuleChainInputNode(org.thingsboard.rule.engine.flow.TbRuleChainInputNode)

Example 8 with RuleChain

use of org.thingsboard.server.common.data.rule.RuleChain in project thingsboard by thingsboard.

the class BaseRuleChainService method importTenantRuleChains.

@Override
public List<RuleChainImportResult> importTenantRuleChains(TenantId tenantId, RuleChainData ruleChainData, boolean overwrite) {
    List<RuleChainImportResult> importResults = new ArrayList<>();
    setRandomRuleChainIds(ruleChainData);
    resetRuleNodeIds(ruleChainData.getMetadata());
    resetRuleChainMetadataTenantIds(tenantId, ruleChainData.getMetadata());
    for (RuleChain ruleChain : ruleChainData.getRuleChains()) {
        RuleChainImportResult importResult = new RuleChainImportResult();
        ruleChain.setTenantId(tenantId);
        ruleChain.setRoot(false);
        if (overwrite) {
            Collection<RuleChain> existingRuleChains = ruleChainDao.findByTenantIdAndTypeAndName(tenantId, Optional.ofNullable(ruleChain.getType()).orElse(RuleChainType.CORE), ruleChain.getName());
            Optional<RuleChain> existingRuleChain = existingRuleChains.stream().findFirst();
            if (existingRuleChain.isPresent()) {
                setNewRuleChainId(ruleChain, ruleChainData.getMetadata(), ruleChain.getId(), existingRuleChain.get().getId());
                ruleChain.setRoot(existingRuleChain.get().isRoot());
                importResult.setUpdated(true);
            }
        }
        try {
            ruleChain = saveRuleChain(ruleChain);
        } catch (Exception e) {
            importResult.setError(ExceptionUtils.getRootCauseMessage(e));
        }
        importResult.setTenantId(tenantId);
        importResult.setRuleChainId(ruleChain.getId());
        importResult.setRuleChainName(ruleChain.getName());
        importResults.add(importResult);
    }
    if (CollectionUtils.isNotEmpty(ruleChainData.getMetadata())) {
        ruleChainData.getMetadata().forEach(md -> saveRuleChainMetaData(tenantId, md));
    }
    return importResults;
}
Also used : RuleChainImportResult(org.thingsboard.server.common.data.rule.RuleChainImportResult) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) ArrayList(java.util.ArrayList) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) DataValidationException(org.thingsboard.server.dao.exception.DataValidationException)

Example 9 with RuleChain

use of org.thingsboard.server.common.data.rule.RuleChain in project thingsboard by thingsboard.

the class RuleChainEntity method toData.

@Override
public RuleChain toData() {
    RuleChain ruleChain = new RuleChain(new RuleChainId(this.getUuid()));
    ruleChain.setCreatedTime(createdTime);
    ruleChain.setTenantId(TenantId.fromUUID(tenantId));
    ruleChain.setName(name);
    ruleChain.setType(type);
    if (firstRuleNodeId != null) {
        ruleChain.setFirstRuleNodeId(new RuleNodeId(firstRuleNodeId));
    }
    ruleChain.setRoot(root);
    ruleChain.setDebugMode(debugMode);
    ruleChain.setConfiguration(configuration);
    ruleChain.setAdditionalInfo(additionalInfo);
    return ruleChain;
}
Also used : RuleChain(org.thingsboard.server.common.data.rule.RuleChain) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId)

Example 10 with RuleChain

use of org.thingsboard.server.common.data.rule.RuleChain in project thingsboard by thingsboard.

the class BaseRuleChainService method deleteRuleChainById.

@Override
@Transactional
public void deleteRuleChainById(TenantId tenantId, RuleChainId ruleChainId) {
    Validator.validateId(ruleChainId, "Incorrect rule chain id for delete request.");
    RuleChain ruleChain = ruleChainDao.findById(tenantId, ruleChainId.getId());
    if (ruleChain != null) {
        if (ruleChain.isRoot()) {
            throw new DataValidationException("Deletion of Root Tenant Rule Chain is prohibited!");
        }
        if (RuleChainType.EDGE.equals(ruleChain.getType())) {
            PageLink pageLink = new PageLink(DEFAULT_PAGE_SIZE);
            PageData<Edge> pageData;
            do {
                pageData = edgeService.findEdgesByTenantIdAndEntityId(tenantId, ruleChainId, pageLink);
                if (pageData != null && pageData.getData() != null && !pageData.getData().isEmpty()) {
                    for (Edge edge : pageData.getData()) {
                        if (edge.getRootRuleChainId() != null && edge.getRootRuleChainId().equals(ruleChainId)) {
                            throw new DataValidationException("Can't delete rule chain that is root for edge [" + edge.getName() + "]. Please assign another root rule chain first to the edge!");
                        }
                    }
                    if (pageData.hasNext()) {
                        pageLink = pageLink.nextPageLink();
                    }
                }
            } while (pageData != null && pageData.hasNext());
        }
    }
    checkRuleNodesAndDelete(tenantId, ruleChainId);
}
Also used : DataValidationException(org.thingsboard.server.dao.exception.DataValidationException) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) PageLink(org.thingsboard.server.common.data.page.PageLink) Edge(org.thingsboard.server.common.data.edge.Edge) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

RuleChain (org.thingsboard.server.common.data.rule.RuleChain)67 RuleChainId (org.thingsboard.server.common.data.id.RuleChainId)26 Test (org.junit.Test)20 RuleNode (org.thingsboard.server.common.data.rule.RuleNode)19 ArrayList (java.util.ArrayList)16 ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)15 RuleChainMetaData (org.thingsboard.server.common.data.rule.RuleChainMetaData)14 ApiOperation (io.swagger.annotations.ApiOperation)13 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)13 Edge (org.thingsboard.server.common.data.edge.Edge)13 TenantId (org.thingsboard.server.common.data.id.TenantId)13 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)11 PageLink (org.thingsboard.server.common.data.page.PageLink)11 RuleNodeId (org.thingsboard.server.common.data.id.RuleNodeId)10 EntityRelation (org.thingsboard.server.common.data.relation.EntityRelation)10 DataValidationException (org.thingsboard.server.dao.exception.DataValidationException)9 EdgeId (org.thingsboard.server.common.data.id.EdgeId)8 List (java.util.List)7 Device (org.thingsboard.server.common.data.Device)7