100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Minor
Rich Turner18bc48ea942f
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.javaindex b5c867814..0c308df5a 100644--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java@@ -220,10 +220,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Consreturn;}- // Send it to the protocol actuator- LOG.fine("Processing asset update: " + assetUpdate);// Its' a send to actuator - push the update to the protocol- // TODO See class Javadoc, should we have a forceUpdate flag?+ LOG.fine("Processing asset update: " + assetUpdate);messageBrokerService.getProducerTemplate().sendBody(ACTUATOR_TOPIC, assetUpdate.getNewState());assetUpdate.setStatus(AssetUpdate.Status.HANDLED);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.javaindex 1482ca36b..68fec0062 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java@@ -20,7 +20,6 @@package org.openremote.manager.server.asset;import org.apache.camel.builder.RouteBuilder;-import org.openremote.agent3.protocol.Protocol;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;@@ -30,85 +29,99 @@ import org.openremote.manager.server.agent.AgentService;import org.openremote.manager.server.agent.ThingAttributes;import org.openremote.manager.server.datapoint.AssetDatapointService;import org.openremote.manager.server.rules.RulesService;-import org.openremote.model.*;+import org.openremote.model.Attribute;+import org.openremote.model.AttributeEvent;+import org.openremote.model.AttributeState;+import org.openremote.model.Attributes;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetType;import org.openremote.model.asset.ThingAttribute;import java.util.ArrayList;import java.util.List;+import java.util.function.Consumer;import java.util.logging.Level;import java.util.logging.Logger;-import java.util.function.Consumer;-import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC;import static org.openremote.agent3.protocol.Protocol.SENSOR_TOPIC;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;import static org.openremote.model.asset.AssetType.THING;/**- * Process asset data changes, routing asset-related messages.+ * Process asset attribute changes, routing asset-related messages.+ *+ * Receives {@link AttributeEvent} messages in {@link #updateAttributeValue(AttributeEvent)} and processes them.+ * <p>+ * {@link AttributeEvent} messages can come from various sources:+ *+ * <ul>+ * <li>Protocol {@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate(AttributeState, long)}</li>+ * <li>User/Client initiated</li>+ * <li>Rules</li>+ * </ul>+ *+ * <p>+ * The {@link AttributeEvent} messages are first validated (link and value type checking) then they are+ * converted into {@link AssetUpdate} messages which are then passed through the processing chain of+ * {@link Consumer<AssetUpdate>}.+ ** <p>- * The regular processor chain is:+ * The regular processing chain is:* <ul>* <li>{@link RulesService}</li>* <li>{@link AgentService}</li>* <li>{@link AssetStorageService}</li>* <li>{@link AssetDatapointService}</li>* </ul>+ ** <p>- * Listens for {@link AttributeEvent} messages on {@link Protocol#SENSOR_TOPIC} and processes them.- * <p>- * Listens for {@link PersistenceEvent} on {@link PersistenceEvent#PERSISTENCE_TOPIC} of {@link Asset}- * entity and detects changed attributes. Any created or updated {@link ThingAttribute} value will be- * send to its {@link Protocol#ACTUATOR_TOPIC}. Any other created or updated attribute will be processed.- * TODO This is not implemented- * <p>- * Accepts client update calls on {@link #updateAttributeValue(AttributeEvent)}. An update event for- * a {@link ThingAttribute} will be send to its {@link Protocol#ACTUATOR_TOPIC}. An update event for- * other attributes will be processed.+ * Rules Service processing logic:* <p>- * TODO What's the call path for thing attribute value updates from clients (northbound, not sensors)?+ * Checks if attribute has {@link org.openremote.model.asset.AssetMeta#RULES_FACT} meta item with value of true and if+ * it does then the message is passed through the rule engines that are in scope for the asset. Rules have the ability+ * to change the status and new value of {@link AssetUpdate} messages to either prevent them from progressing through+ * the processing chain or changing the value that progresses through the processing chain. Rules can also set a status+ * of {@link AssetUpdate.Status#RULES_HANDLED} which means that the message shouldn't be processed by any more rule+ * engines but it should continue through the processing chain.+ ** <p>- * Proposal:+ * Agent service processing logic:* <p>- * 1. Receive AttributeEvent on client API+ * When the incoming messages come from a Protocol (i.e. generated by a call from+ * {@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate(AttributeState, long)} then+ * the Agent Service will ignore the message and just pass it onto the next consumer.+ *+ * When the incoming messages come from any other source then the Agent Service will check if it relates+ * to a THING asset and if so it will check if the attribute is linked to an agent. If it is not linked to+ * an Agent then it ignores the message and just passes it to the next consumer. If it is linked to an Agent+ * and the Agent link is invalid then the message status is set to {@link AssetUpdate.Status#ERROR} and+ * the message will not be able to progress through the processing chain.+ *+ * If the message is for a valid linked agent then a message is sent on the+ * {@link org.openremote.agent3.protocol.AbstractProtocol#ACTUATOR_TOPIC} which the Protocol will receive in+ * {@link org.openremote.agent3.protocol.AbstractProtocol#sendToActuator(AttributeEvent)}.+ ** <p>- * 2. Handle security and verify the message is for a linked agent/thing/attribute in the asset database+ * This means that a protocol implementation is responsible for producing a new {@link AttributeEvent} to+ * indicate to the system that the attribute value has/has not changed. The protocol should know best when to+ * do this and will vary from protocol to protocol; some 'things' might respond to an actuator command, or they+ * might send a separate sensor changed message or both or neither (fire and forget) the protocol must decide+ * what the best course of action is based on the 'things' it communicates with and the transport layer it uses etc.* <p>- * 3. Send the AttributeEvent to the Protocol through ACTUATOR_TOPIC and trigger device/service call+ ** <p>- * 4a. We assume that most protocol implementations are not using fire-and-forget but request/reply- * communication. Thus, an AttributeEvent has no further consequences besides triggering an- * actuator. We expect that a sensor "response" will let us know "soon" if the call was successful.- * Only a sensor value change will result in an update of the asset database state. The window of- * inconsistency we can accept depends on how "soon" a protocol typically responds.+ * Asset Storage Service processing logic:* <p>- * 4b. Alternatively, if the updated attribute is configured with the "forceUpdate" meta item, we write- * the new attribute state directly into the asset database after triggering the actuator. This flag- * is useful if the protocol does not reflect actuator changes "immediately". For example, if we- * send a value to a light dimmer actuator, does the light dimmer also have a sensor that responds- * quickly with the new value? If the device/service does not reply to value changes, we can force- * an update of the "current state" in our database and simply assume that the actuator call was+ * Always tries to persist the attribute value in the DB and allows the message to continue if the commit was* successful.- * <p>- * 4c. Should "forceUpdate" be the default behavior?- *- * The {@link Protocol} could be in the processing chain (via {@link org.openremote.manager.server.agent.AgentService})- * and then the protocol can decide whether to mark the asset update as handled or not so then attribute- * event either makes it to the {@link AssetStorageService} or it doesn't...the protocol should know what is- * best (i.e. it should know if the sensor value will update instantly or in N seconds).- *- * Question then is where in the processing chain should it go, the following would give rules the opportunity- * to prevent the attribute change which could be nice:*- * <ul>- * <li>{@link RulesService}</li>- * <li>{@link org.openremote.manager.server.agent.AgentService} (only process thing attribute events linked to protocols)</li>- * <li>{@link AssetStorageService}</li>- * <li>{@link AssetDatapointService}</li>- * </ul>+ * <p>+ * Asset Datapoint Service processing logic:+ * <p>+ * Checks if attribute has {@link org.openremote.model.asset.AssetMeta#STORE_DATA_POINTS} meta item with a value of true+ * and if it does then the {@link AttributeEvent} is stored in a time series DB. Then allows the message to continue+ * if the commit was successful.*/public class AssetProcessingService extends RouteBuilder implements ContainerService {@@ -306,6 +319,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSercase ERROR:// TODO Better error handling, not sure we need rewind?LOG.severe("Asset update status is '" + assetUpdate.getStatus() + "' cannot continue processing");+ assetUpdate.setStatus(AssetUpdate.Status.COMPLETED);throw new RuntimeException("Processor " + processor + " error: " + assetUpdate, assetUpdate.getError());}}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.javaindex 389571e6c..179b77b4e 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.java@@ -49,7 +49,13 @@ public class AssetUpdate {/*** Processor encountered an error trying to process the update, cancel further processing and escalate.*/- ERROR+ ERROR,++ /**+ * Indicates that this update has been through the entire processing chain; the object can no longer be+ * mutated at this stage+ */+ COMPLETED}final protected ServerAsset asset;diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.javaindex 615127b44..bf64a0a4e 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java@@ -19,6 +19,7 @@*/package org.openremote.manager.server.rules;+import elemental.json.Json;import org.kie.api.KieServices;import org.kie.api.builder.KieBuilder;import org.kie.api.builder.KieFileSystem;@@ -32,9 +33,10 @@ import org.kie.api.conf.EventProcessingOption;import org.kie.api.runtime.KieContainer;import org.kie.api.runtime.KieSession;import org.kie.api.runtime.KieSessionConfiguration;+import org.kie.api.runtime.conf.ClockTypeOption;import org.kie.api.runtime.conf.TimedRuleExectionOption;import org.kie.api.runtime.rule.FactHandle;-import org.openremote.container.Container;+import org.kie.api.time.SessionClock;import org.openremote.manager.server.asset.AssetUpdate;import org.openremote.manager.shared.rules.RulesDefinition;import org.openremote.model.AttributeRef;@@ -49,24 +51,25 @@ import java.util.logging.Level;import java.util.logging.Logger;public class RulesDeployment<T extends RulesDefinition> {-public static final Logger LOG = Logger.getLogger(RulesDeployment.class.getName());+ // This is here so Clock Type can be set to pseudo from tests+ protected static ClockTypeOption DefaultClockType;private static final int AUTO_START_DELAY_SECONDS = 2;private static Long counter = 1L;static final protected RuleUtil ruleUtil = new RuleUtil();- protected Map<Long, T> ruleDefinitions = new LinkedHashMap<>();- protected RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();+ protected final Map<Long, T> ruleDefinitions = new LinkedHashMap<>();+ protected final RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();protected KieSession knowledgeSession;protected KieServices kieServices;protected KieFileSystem kfs;// We need to be able to reference the KieModule dynamically generated for this engine// from the singleton KieRepository to do this we need a pom.xml file with a release ID - crazy drools!!protected ReleaseId releaseId;- protected String id;+ protected final String id;protected boolean error;protected boolean running;protected long currentFactCount;- protected Class<T> clazz;+ protected final Class<T> clazz;final protected Map<AttributeRef, FactHandle> attributeFacts = new HashMap<>();protected static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();protected ScheduledFuture startTimer;@@ -76,12 +79,11 @@ public class RulesDeployment<T extends RulesDefinition> {this.id = id;}- protected static Long getNextCounter() {- synchronized (counter) {- return counter++;- }+ protected synchronized static Long getNextCounter() {+ return counter++;}+ @SuppressWarnings("unchecked")public synchronized T[] getAllRulesDefinitions() {T[] arr = (T[]) Array.newInstance(clazz, 0);return ruleDefinitions.values().toArray(arr);@@ -103,6 +105,15 @@ public class RulesDeployment<T extends RulesDefinition> {return knowledgeSession;}+ public SessionClock getSessionClock() {+ KieSession session = getKnowledgeSession();+ if (session != null) {+ return session.getSessionClock();+ }++ return null;+ }+public synchronized boolean isEmpty() {return ruleDefinitions.isEmpty();}@@ -133,28 +144,7 @@ public class RulesDeployment<T extends RulesDefinition> {}if (kfs == null) {- // Initialise- kieServices = KieServices.Factory.get();- KieModuleModel kieModuleModel = kieServices.newKieModuleModel();-- String versionId = getNextCounter().toString();- releaseId = kieServices.newReleaseId("org.openremote", "openremote-kiemodule", versionId);- KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKModule");- kieBaseModel- .setDefault(true)- .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)- .setEventProcessingMode(EventProcessingOption.STREAM)- .newKieSessionModel("ksession1")- .setDefault(true)- .setType(KieSessionModel.KieSessionType.STATEFUL);- // TODO: Provide mechanism for configuring the clock per rule engine- //.setClockType();- kfs = kieServices.newKieFileSystem();- kfs.generateAndWritePomXML(releaseId);- kfs.writeKModuleXML(kieModuleModel.toXML());-- LOG.fine("Initialised rules service for deployment '" + getId() + "'");- LOG.info(kieBaseModel.toString());+ initialiseEngine();}T existingDefinition = ruleDefinitions.get(rulesDefinition.getId());@@ -178,6 +168,7 @@ public class RulesDeployment<T extends RulesDefinition> {if (existingDefinition != null) {// Remove this old rules filekfs.delete("src/main/resources/" + rulesDefinition.getId());+ //noinspection SuspiciousMethodCallsruleDefinitions.remove(existingDefinition);}@@ -240,7 +231,6 @@ public class RulesDeployment<T extends RulesDefinition> {return;}- // TODO: What is the best way to handle live deployment of new rulesif (isRunning()) {stop();}@@ -276,6 +266,32 @@ public class RulesDeployment<T extends RulesDefinition> {}}+ protected void initialiseEngine() {+ // Initialise+ kieServices = KieServices.Factory.get();+ KieModuleModel kieModuleModel = kieServices.newKieModuleModel();++ String versionId = getNextCounter().toString();+ releaseId = kieServices.newReleaseId("org.openremote", "openremote-kiemodule", versionId);+ KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKModule");+ ClockTypeOption clockType = DefaultClockType != null ? DefaultClockType : ClockTypeOption.get("realtime");++ kieBaseModel+ .setDefault(true)+ .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)+ .setEventProcessingMode(EventProcessingOption.STREAM)+ .newKieSessionModel("ksession1")+ .setDefault(true)+ .setType(KieSessionModel.KieSessionType.STATEFUL)+ .setClockType(clockType);+ kfs = kieServices.newKieFileSystem();+ kfs.generateAndWritePomXML(releaseId);+ kfs.writeKModuleXML(kieModuleModel.toXML());++ LOG.fine("Initialised rules service for deployment '" + getId() + "'");+ LOG.info(kieBaseModel.toString());+ }+protected synchronized void start() {if (isRunning()) {return;@@ -305,7 +321,7 @@ public class RulesDeployment<T extends RulesDefinition> {knowledgeSession = kieContainer.newKieSession(kieSessionConfiguration);setGlobal("util", ruleUtil);- setGlobal("JSON", Container.JSON);+ setGlobal("JSON", Json.instance());setGlobal("LOG", LOG);knowledgeSession.addEventListener(ruleExecutionLogger);@@ -336,7 +352,15 @@ public class RulesDeployment<T extends RulesDefinition> {running = false;}- protected void processUpdate(AssetUpdate assetUpdate) {+ protected synchronized void processUpdate(AssetUpdate assetUpdate) {+ if (isError()) {+ LOG.warning("Rules engine is in error state so cannot process update event: " + this);+ return;+ } else if (!isRunning()) {+ LOG.warning("Rules engine is not running so cannot process update event:" + this);+ return;+ }+long newFactCount;AttributeRef attributeRef = assetUpdate.getNewState().getAttributeRef();diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.javaindex 7a6b5bd13..413826ab0 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java@@ -20,7 +20,6 @@package org.openremote.manager.server.rules;import org.apache.camel.builder.RouteBuilder;-import org.openremote.agent3.protocol.AbstractProtocol;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerSetupService;@@ -133,12 +132,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons@Overridepublic void accept(AssetUpdate assetUpdate) {- // If update was initiated by a protocol then rules shouldn't be allowed to prevent it- // the update from progressing through the system- if (AbstractProtocol.class.isAssignableFrom(assetUpdate.getSender())) {- // TODO: Prevent rules RHS from blocking protocol initiated updates- }-processAssetUpdate(assetUpdate);}@@ -198,53 +191,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons}}-// protected boolean addResource(Resource resource, KieServices kieServices, KieFileSystem kfs) {-// String sourcePath = resource.getSourcePath();-// if (sourcePath == null) {-// throw new IllegalArgumentException("Resource definition must have source path: " + resource);-// }-// LOG.info("Adding rule definition: " + resource);-// try {-//-// // TODO Drools config API is shit, this is hidden in some internal code-// if (ResourceType.DTABLE.matchesExtension(sourcePath)) {-// int lastDot = sourcePath.lastIndexOf('.');-// if (lastDot >= 0 && sourcePath.length() > lastDot + 1) {-// String extension = sourcePath.substring(lastDot + 1);-// DecisionTableConfiguration tableConfig = KnowledgeBuilderFactory.newDecisionTableConfiguration();-// tableConfig.setInputType(DecisionTableInputType.valueOf(extension.toUpperCase()));-// resource.setConfiguration(tableConfig);-// }-// }-//-// LOG.fine("Rule definition resource config: " + resource.getConfiguration().toProperties());-// kfs.write("src/main/resources/" + sourcePath, resource);-// KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();-//-// if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {-// Collection<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);-// LOG.severe("Error in rule definition: " + resource);-// for (Message error : errors) {-// LOG.severe(error.getText());-// }-// // If compilation failed, remove rules from FileSystem so it won't fail on next pass here if any-// kfs.delete("src/main/resources/" + sourcePath);-// } else {-// LOG.info("Added rule definition: " + resource);-// return true;-// }-// } catch (Throwable t) {-// LOG.log(-// Level.SEVERE,-// "Error in rule definition: " + resource,-// t-// );-// // If compilation failed, remove rules from FileSystem so it won't fail on next pass here if any-// kfs.delete("src/main/resources/" + sourcePath);-// }-// return false;-// }-protected synchronized void deployGlobalRulesDefinition(GlobalRulesDefinition rulesDefinition) {// Global rules have access to everything in the systemif (globalDeployment == null) {@@ -315,7 +261,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons});}-protected void deployAssetRulesDefinition(AssetRulesDefinition rulesDefinition) {// Look for existing deployment for this assetRulesDeployment<AssetRulesDefinition> deployment = assetDeployments@@ -369,22 +314,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// Pass through each engine if an engine is in error state then log and skip itfor (RulesDeployment deployment : rulesDeployments) {- synchronized (deployment) {- if (deployment.isError()) {- LOG.warning("Rules engine is in error state so cannot process update event: " + deployment);- } else if (!deployment.isRunning()) {- LOG.warning("Rules engine is not running so cannot process update event:" + deployment);- } else {- // TODO: Handle any exceptions in rule RHS- deployment.processUpdate(assetUpdate);- if (assetUpdate.getStatus() != AssetUpdate.Status.CONTINUE) {- LOG.info("Rules engine has marked update event as '" + assetUpdate.getStatus() + "' so not processing anymore");- if (assetUpdate.getStatus() == AssetUpdate.Status.RULES_HANDLED) {- assetUpdate.setStatus(AssetUpdate.Status.CONTINUE);- }- break;- }+ deployment.processUpdate(assetUpdate);+ if (assetUpdate.getStatus() != AssetUpdate.Status.CONTINUE) {+ LOG.info("Rules engine has marked update event as '" + assetUpdate.getStatus() + "' so not processing anymore");+ if (assetUpdate.getStatus() == AssetUpdate.Status.RULES_HANDLED) {+ assetUpdate.setStatus(AssetUpdate.Status.CONTINUE);}+ break;}}}diff --git a/manager/test/src/test/resources/org/openremote/test/rules/TestRuleFiring.drl b/manager/test/src/test/resources/org/openremote/test/rules/TestRuleFiring.drldeleted file mode 100644index 170f30980..000000000--- a/manager/test/src/test/resources/org/openremote/test/rules/TestRuleFiring.drl+++ /dev/null@@ -1,25 +0,0 @@-package org.openremote.test.rules;--import org.openremote.model.*;--declare CallCounter- count : int-end--rule "Insert Counter Fact"-when- not $counter:CallCounter()-then- // Insert Call Counter- CallCounter counter = new CallCounter();- insert(counter);-end--rule "TestRuleFiring"-when- $e: AttributeStateChange( entityName == RuleExecutionLoggerTest.TEST_ENTITY_ID, attribute.name == RuleExecutionLoggerTest.TEST_ATTRIBUTE_NAME)- $counter : CallCounter()-then- // Update call count fact-end-