Search in sources :

Example 36 with RuleChain

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

the class RuleChainController method saveRuleChain.

@ApiOperation(value = "Create Or Update Rule Chain (saveRuleChain)", notes = "Create or update the Rule Chain. When creating Rule Chain, platform generates Rule Chain Id as " + UUID_WIKI_LINK + "The newly created Rule Chain Id will be present in the response. " + "Specify existing Rule Chain id to update the rule chain. " + "Referencing non-existing rule chain Id will cause 'Not Found' error." + "\n\n" + RULE_CHAIN_DESCRIPTION + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/ruleChain", method = RequestMethod.POST)
@ResponseBody
public RuleChain saveRuleChain(@ApiParam(value = "A JSON value representing the rule chain.") @RequestBody RuleChain ruleChain) throws ThingsboardException {
    try {
        boolean created = ruleChain.getId() == null;
        ruleChain.setTenantId(getCurrentUser().getTenantId());
        checkEntity(ruleChain.getId(), ruleChain, Resource.RULE_CHAIN);
        RuleChain savedRuleChain = checkNotNull(ruleChainService.saveRuleChain(ruleChain));
        if (RuleChainType.CORE.equals(savedRuleChain.getType())) {
            tbClusterService.broadcastEntityStateChangeEvent(ruleChain.getTenantId(), savedRuleChain.getId(), created ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED);
        }
        logEntityAction(savedRuleChain.getId(), savedRuleChain, null, created ? ActionType.ADDED : ActionType.UPDATED, null);
        if (RuleChainType.EDGE.equals(savedRuleChain.getType())) {
            if (!created) {
                sendEntityNotificationMsg(savedRuleChain.getTenantId(), savedRuleChain.getId(), EdgeEventActionType.UPDATED);
            }
        }
        return savedRuleChain;
    } catch (Exception e) {
        logEntityAction(emptyId(EntityType.RULE_CHAIN), ruleChain, null, ruleChain.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e);
        throw handleException(e);
    }
}
Also used : RuleChain(org.thingsboard.server.common.data.rule.RuleChain) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 37 with RuleChain

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

the class RuleChainController method setRootRuleChain.

@ApiOperation(value = "Set Root Rule Chain (setRootRuleChain)", notes = "Makes the rule chain to be root rule chain. Updates previous root rule chain as well. " + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/ruleChain/{ruleChainId}/root", method = RequestMethod.POST)
@ResponseBody
public RuleChain setRootRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
    checkParameter(RULE_CHAIN_ID, strRuleChainId);
    try {
        RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
        RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE);
        TenantId tenantId = getCurrentUser().getTenantId();
        RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId);
        if (ruleChainService.setRootRuleChain(getTenantId(), ruleChainId)) {
            if (previousRootRuleChain != null) {
                previousRootRuleChain = ruleChainService.findRuleChainById(getTenantId(), previousRootRuleChain.getId());
                tbClusterService.broadcastEntityStateChangeEvent(previousRootRuleChain.getTenantId(), previousRootRuleChain.getId(), ComponentLifecycleEvent.UPDATED);
                logEntityAction(previousRootRuleChain.getId(), previousRootRuleChain, null, ActionType.UPDATED, null);
            }
            ruleChain = ruleChainService.findRuleChainById(getTenantId(), ruleChainId);
            tbClusterService.broadcastEntityStateChangeEvent(ruleChain.getTenantId(), ruleChain.getId(), ComponentLifecycleEvent.UPDATED);
            logEntityAction(ruleChain.getId(), ruleChain, null, ActionType.UPDATED, null);
        }
        return ruleChain;
    } catch (Exception e) {
        logEntityAction(emptyId(EntityType.RULE_CHAIN), null, null, ActionType.UPDATED, e, strRuleChainId);
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 38 with RuleChain

use of org.thingsboard.server.common.data.rule.RuleChain 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 39 with RuleChain

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

the class RuleChainActorMessageProcessor method initRoutes.

private void initRoutes(RuleChain ruleChain, List<RuleNode> ruleNodeList) {
    nodeRoutes.clear();
    // Populating the routes map;
    for (RuleNode ruleNode : ruleNodeList) {
        List<EntityRelation> relations = service.getRuleNodeRelations(TenantId.SYS_TENANT_ID, ruleNode.getId());
        log.trace("[{}][{}][{}] Processing rule node relations [{}]", tenantId, entityId, ruleNode.getId(), relations.size());
        if (relations.size() == 0) {
            nodeRoutes.put(ruleNode.getId(), Collections.emptyList());
        } else {
            for (EntityRelation relation : relations) {
                log.trace("[{}][{}][{}] Processing rule node relation [{}]", tenantId, entityId, ruleNode.getId(), relation.getTo());
                if (relation.getTo().getEntityType() == EntityType.RULE_NODE) {
                    RuleNodeCtx ruleNodeCtx = nodeActors.get(new RuleNodeId(relation.getTo().getId()));
                    if (ruleNodeCtx == null) {
                        throw new IllegalArgumentException("Rule Node [" + relation.getFrom() + "] has invalid relation to Rule node [" + relation.getTo() + "]");
                    }
                }
                nodeRoutes.computeIfAbsent(ruleNode.getId(), k -> new ArrayList<>()).add(new RuleNodeRelation(ruleNode.getId(), relation.getTo(), relation.getType()));
            }
        }
    }
    firstId = ruleChain.getFirstRuleNodeId();
    firstNode = nodeActors.get(firstId);
    state = ComponentLifecycleState.ACTIVE;
}
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) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) ArrayList(java.util.ArrayList) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId)

Example 40 with RuleChain

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

the class RuleChainEdgeProcessor method processRuleChainToEdge.

public DownlinkMsg processRuleChainToEdge(Edge edge, EdgeEvent edgeEvent, UpdateMsgType msgType, EdgeEventActionType action) {
    RuleChainId ruleChainId = new RuleChainId(edgeEvent.getEntityId());
    DownlinkMsg downlinkMsg = null;
    switch(action) {
        case ADDED:
        case UPDATED:
        case ASSIGNED_TO_EDGE:
            RuleChain ruleChain = ruleChainService.findRuleChainById(edgeEvent.getTenantId(), ruleChainId);
            if (ruleChain != null) {
                RuleChainUpdateMsg ruleChainUpdateMsg = ruleChainMsgConstructor.constructRuleChainUpdatedMsg(edge.getRootRuleChainId(), msgType, ruleChain);
                downlinkMsg = DownlinkMsg.newBuilder().setDownlinkMsgId(EdgeUtils.nextPositiveInt()).addRuleChainUpdateMsg(ruleChainUpdateMsg).build();
            }
            break;
        case DELETED:
        case UNASSIGNED_FROM_EDGE:
            downlinkMsg = DownlinkMsg.newBuilder().setDownlinkMsgId(EdgeUtils.nextPositiveInt()).addRuleChainUpdateMsg(ruleChainMsgConstructor.constructRuleChainDeleteMsg(ruleChainId)).build();
            break;
    }
    return downlinkMsg;
}
Also used : DownlinkMsg(org.thingsboard.server.gen.edge.v1.DownlinkMsg) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) RuleChainUpdateMsg(org.thingsboard.server.gen.edge.v1.RuleChainUpdateMsg)

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