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
Rules and Asset processing updates
Rich Turnerb2dc53870463
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 68fec0062..e4104f240 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@@ -24,7 +24,6 @@ import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;-import org.openremote.container.persistence.PersistenceEvent;import org.openremote.manager.server.agent.AgentService;import org.openremote.manager.server.agent.ThingAttributes;import org.openremote.manager.server.datapoint.AssetDatapointService;@@ -33,7 +32,6 @@ 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;@@ -44,8 +42,6 @@ import java.util.logging.Level;import java.util.logging.Logger;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;/**@@ -170,15 +166,6 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer.process(exchange -> {processSensorUpdate(exchange.getIn().getBody(AttributeEvent.class));});-- // If any asset was modified in the database, detect changed attributes- from(PERSISTENCE_TOPIC)- .filter(isPersistenceEventForEntityType(Asset.class))- .process(exchange -> {- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);- Asset asset = (Asset) persistenceEvent.getEntity();- // TODO: Detect which attribute was created/updated in the database and handle it- });}/**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 7ebdefd13..9bc160a90 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@@ -82,14 +82,19 @@ public class AssetUpdate {if (!newState.getAttributeRef().getAttributeName().equals(attribute.getName())) {throw new IllegalArgumentException("New state attribute name must match: " + attribute);}- if (!oldState.getAttributeRef().getEntityId().equals(asset.getId())) {- throw new IllegalArgumentException("Old state entity ID must match: " + asset);- }- if (!oldState.getAttributeRef().getAttributeName().equals(attribute.getName())) {- throw new IllegalArgumentException("Old state attribute name must match: " + attribute);++ if (oldState != null) {+ if (!oldState.getAttributeRef().getEntityId().equals(asset.getId())) {+ throw new IllegalArgumentException("Old state entity ID must match: " + asset);+ }+ if (!oldState.getAttributeRef().getAttributeName().equals(attribute.getName())) {+ throw new IllegalArgumentException("Old state attribute name must match: " + attribute);+ }++ oldState.getAttributeRef().setEntityName(asset.getName());}+newState.getAttributeRef().setEntityName(asset.getName());- oldState.getAttributeRef().setEntityName(asset.getName());}public ServerAsset getAsset() {@@ -151,7 +156,8 @@ public class AssetUpdate {AssetUpdate that = (AssetUpdate) o;- return oldState.equals(that.oldState) && newState.equals(that.newState);+ return ((oldState == null && that.oldState == null) || (oldState != null && that.oldState != null && oldState.equals(that.oldState)))+ && ((newState == null && that.newState == null) || (newState != null && that.newState != null && newState.equals(that.newState)));}@Overridediff --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 bf64a0a4e..09b75f551 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@@ -20,6 +20,7 @@package org.openremote.manager.server.rules;import elemental.json.Json;+import org.drools.core.factmodel.Fact;import org.kie.api.KieServices;import org.kie.api.builder.KieBuilder;import org.kie.api.builder.KieFileSystem;@@ -40,6 +41,7 @@ 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;+import org.openremote.model.asset.Asset;import java.lang.reflect.Array;import java.util.*;@@ -70,7 +72,7 @@ public class RulesDeployment<T extends RulesDefinition> {protected boolean running;protected long currentFactCount;protected final Class<T> clazz;- final protected Map<AttributeRef, FactHandle> attributeFacts = new HashMap<>();+ final protected Map<AssetUpdate, FactHandle> facts = new HashMap<>();protected static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();protected ScheduledFuture startTimer;@@ -179,6 +181,8 @@ public class RulesDeployment<T extends RulesDefinition> {try {// ID will be unique within the scope of a rules deployment as rules definition will all be of same typekfs.write("src/main/resources/" + rulesDefinition.getId() + ".drl", rulesDefinition.getRules());+ // Unload the rules string from the definition we don't need it anymore and don't want it using memory+ rulesDefinition.setRules(null);KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {@@ -325,6 +329,11 @@ public class RulesDeployment<T extends RulesDefinition> {setGlobal("LOG", LOG);knowledgeSession.addEventListener(ruleExecutionLogger);++ // Insert all the facts into the session+ Set<Map.Entry<AssetUpdate, FactHandle>> factEntries = facts.entrySet();+ facts.clear();+ factEntries.forEach(factEntry -> insertFactIntoSession(factEntry.getKey()));} catch (Throwable t) {error = true;throw new RuntimeException(t);@@ -348,61 +357,74 @@ public class RulesDeployment<T extends RulesDefinition> {LOG.fine("Knowledge session disposed");}- attributeFacts.clear();+ facts.clear();running = false;}- 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;+ protected synchronized void insertFact(AssetUpdate assetUpdate) {+ // Check if fact already exists using equals()+ if (!facts.containsKey(assetUpdate)) {+ // Delete any existing fact for this attribute ref+ // Put the fact into working memory and store the handle+ retractFact(assetUpdate);+ insertFactIntoSession(assetUpdate);}+ }- long newFactCount;+ protected synchronized void retractFact(AssetUpdate assetUpdate) {AttributeRef attributeRef = assetUpdate.getNewState().getAttributeRef();- // If this fact is not in working memory (considering its equals() method)...- if (!knowledgeSession.getObjects().contains(assetUpdate)) {- // If there already is a fact in working memory for this attribute then delete it- FactHandle factHandle = attributeFacts.get(attributeRef);-- if (factHandle != null) {- try {- // ... retract it from working memory ...- LOG.finest("Removed stale attribute fact: " + attributeRef);- knowledgeSession.delete(factHandle);- } finally {- // ... and make sure we don't keep a reference to the stale fact- attributeFacts.remove(attributeRef);- }+ // If there already is a fact in working memory for this attribute then delete it+ AssetUpdate update = facts.keySet()+ .stream()+ .filter(au -> au.getAttribute().getAttributeRef(au.getEntityId()).equals(attributeRef))+ .findFirst()+ .orElse(null);++ FactHandle factHandle = update != null ? facts.get(update) : null;++ if (factHandle != null && knowledgeSession != null) {+ try {+ // ... retract it from working memory ...+ LOG.finest("Removed stale attribute fact: " + attributeRef);+ knowledgeSession.delete(factHandle);+ } finally {+ // ... and make sure we don't keep a reference to the stale fact+ facts.remove(update);}+ }- // Put the fact into working memory and store the handle- boolean isUpdate = factHandle != null;+ return;+ }++ protected FactHandle insertFactIntoSession(AssetUpdate assetUpdate) {+ FactHandle factHandle = null;++ if (!isError() && isRunning()) {+ long newFactCount;factHandle = knowledgeSession.insert(assetUpdate);- attributeFacts.put(attributeRef, factHandle);- LOG.finest("On " + this + ", fact " + (isUpdate ? "updated: " : "inserted: " + assetUpdate));- }+ facts.put(assetUpdate, factHandle);+ LOG.finest("Inserted fact into session");++ LOG.finest("On " + this + ", firing all rules");+ int fireCount = knowledgeSession.fireAllRules();+ LOG.finest("On " + this + ", fired rules count: " + fireCount);++ // TODO: Prevent run away fact creation (not sure how we can do this reliably as facts can be generated in rule RHS)+ // MR: this is heuristic number which comes good for finding facts memory leak in the drl file.+ // problem - when you are not careful then drl can insert new facts till memory exhaustion. As there+ // are usually few 100 facts in drl's I'm working with, putting arbitrary number gives me early feedback+ // that there is potential problem. Perhaps we should think about a better solution to this problem?+ newFactCount = knowledgeSession.getFactCount();+ LOG.finest("On " + this + ", new fact count: " + newFactCount);+ if (newFactCount != currentFactCount) {+ LOG.finest("On " + this + ", fact count changed from " + currentFactCount + " to " + newFactCount + " after: " + assetUpdate);+ }- LOG.finest("On " + this + ", firing all rules");- int fireCount = knowledgeSession.fireAllRules();- LOG.finest("On " + this + ", fired rules count: " + fireCount);-- // TODO: Prevent run away fact creation (not sure how we can do this reliably as facts can be generated in rule RHS)- // MR: this is heuristic number which comes good for finding facts memory leak in the drl file.- // problem - when you are not careful then drl can insert new facts till memory exhaustion. As there- // are usually few 100 facts in drl's I'm working with, putting arbitrary number gives me early feedback- // that there is potential problem. Perhaps we should think about a better solution to this problem?- newFactCount = knowledgeSession.getFactCount();- LOG.finest("On " + this + ", new fact count: " + newFactCount);- if (newFactCount != currentFactCount) {- LOG.finest("On " + this + ", fact count changed from " + currentFactCount + " to " + newFactCount + " after: " + assetUpdate);+ currentFactCount = newFactCount;}- currentFactCount = newFactCount;+ return factHandle;}@Overridediff --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 a9ef46ae2..3aea705f5 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@@ -35,6 +35,9 @@ import org.openremote.manager.shared.rules.GlobalRulesDefinition;import org.openremote.manager.shared.rules.RulesDefinition;import org.openremote.manager.shared.rules.TenantRulesDefinition;import org.openremote.manager.shared.security.Tenant;+import org.openremote.model.Attributes;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetMeta;import java.util.*;import java.util.function.Consumer;@@ -52,7 +55,7 @@ import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceE* Global Definitions* Tenant Definitions* Asset Definitions (in hierarchical order from oldest ancestor down - ordering of- * asset definitions with same parent asset are not guaranteed also processing of definitions+ * asset definitions with same parent asset are not guaranteed also processing order of definitions* with the same scope is not guaranteed)*/public class RulesService extends RouteBuilder implements ContainerService, Consumer<AssetUpdate> {@@ -94,6 +97,46 @@ public class RulesService extends RouteBuilder implements ContainerService, ConsTenant tenant = (Tenant) persistenceEvent.getEntity();processTenantChange(tenant, persistenceEvent.getCause());});++ // If any asset was modified in the database, detect changed attributes+ from(PERSISTENCE_TOPIC)+ .filter(isPersistenceEventForEntityType(Asset.class))+ .process(exchange -> {+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ Asset asset = (Asset) persistenceEvent.getEntity();+ ServerAsset serverAsset = ServerAsset.map(asset, new ServerAsset());++ switch (persistenceEvent.getCause())+ {+ case INSERT:+ // New asset has been created so get attributes that have RULES_FACT meta+ Attributes addedAttributes = new Attributes(asset.getAttributes());+ Arrays.stream(addedAttributes.get())+ .filter(attribute -> attribute.hasMetaItem(AssetMeta.RULES_FACT))+ .forEach(attribute -> {+ AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);+ // TODO: What if a rule engine marks the fact as handled it should still go into other engines here???+ insertFact(update);+ });+ break;+ case UPDATE:+ // TODO: Handle update case+ break;+ case DELETE:+ // Retract any facts that were associated with this asset+ Attributes removedAttributes = new Attributes(asset.getAttributes());+ Arrays.stream(removedAttributes.get())+ .filter(attribute -> attribute.hasMetaItem(AssetMeta.RULES_FACT))+ .forEach(attribute -> {+ AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);+ // TODO: What if a rule engine marks the fact as handled it should still go into other engines here???+ retractFact(update);+ });+ break;+ }+ // TODO: Detect which attribute was created/updated in the database and handle it++ });}@Override@@ -112,6 +155,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// Deploy asset rules - group by assetID then tenant then order hierarchicallydeployAssetRulesDefinitions(rulesStorageService.findEnabledAssetDefinitions());++ // TODO: Look for attributes that contain RULES_FACT meta and push Attribute Events for them+ // into the rule engines.}@Override@@ -132,7 +178,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons@Overridepublic void accept(AssetUpdate assetUpdate) {- processAssetUpdate(assetUpdate);+ insertFact(assetUpdate);}public synchronized void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {@@ -253,9 +299,10 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.forEach(es -> {List<Pair<ServerAsset, List<AssetRulesDefinition>>> tenantAssetAndRules = es.getValue();+ // RT: Not sure we need ordering here for starting engines so removing it// Order rules definitions by asset hierarchy within this tenanttenantAssetAndRules.stream()- .sorted(Comparator.comparingInt(item -> item.key.getPath().length))+ //.sorted(Comparator.comparingInt(item -> item.key.getPath().length)).flatMap(assetAndRules -> assetAndRules.value.stream()).forEach(this::deployAssetRulesDefinition);});@@ -284,11 +331,44 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons}}- protected synchronized void processAssetUpdate(AssetUpdate assetUpdate) {+ // TODO: What should we do when inserting facts into engines that aren't running? should we update the status to error?+ protected synchronized void insertFact(AssetUpdate assetUpdate) {+ // TODO: implement rules processing error state handling++ // Get the chain of rule engines that we need to pass through+ ServerAsset asset = assetUpdate.getAsset();+ List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getPath());++ // Pass through each engine and try and insert the fact+ for (RulesDeployment deployment : rulesDeployments) {+ deployment.insertFact(assetUpdate);++ // We have to check status between each engine insert as a rule in the engine could have updated+ // the status+ 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;+ }+ }+ }++ protected void retractFact(AssetUpdate assetUpdate) {// TODO: implement rules processing error state handling// Get the chain of rule engines that we need to pass throughServerAsset asset = assetUpdate.getAsset();+ List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getPath());++ // Pass through each engine and retract this fact+ for (RulesDeployment deployment : rulesDeployments) {+ deployment.retractFact(assetUpdate);+ }+ }++ protected List<RulesDeployment> getEnginesInScope(String assetRealmId, String[] assetPath) {List<RulesDeployment> rulesDeployments = new ArrayList<>();// Add global engine (if it exists)@@ -297,7 +377,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons}// Add tenant engine (if it exists)- RulesDeployment tenantDeployment = tenantDeployments.get(asset.getRealmId());+ RulesDeployment tenantDeployment = tenantDeployments.get(assetRealmId);if (tenantDeployment != null) {rulesDeployments.add(tenantDeployment);@@ -305,24 +385,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// Add asset engines// Iterate through asset hierarchy using asset IDs from getPath- for (String assetId : asset.getPath()) {+ for (String assetId : assetPath) {RulesDeployment assetDeployment = assetDeployments.get(assetId);if (assetDeployment != null) {rulesDeployments.add(assetDeployment);}}- // Pass through each engine if an engine is in error state then log and skip it- for (RulesDeployment deployment : rulesDeployments) {- 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;- }- }+ return rulesDeployments;}@Overridediff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovyindex 6410fb467..4ecd09f28 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy@@ -38,6 +38,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitgiven: "expected conditions"def conditions = new PollingConditions(timeout: 10, delay: 1)+ // TODO: Update this to use Simulator Protocoland: "a mock protocol"def mockProtocolName = Constants.PROTOCOL_NAMESPACE + ":mockProtocol"def protocolDeployed = falsediff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovyindex 4ad0cfc9e..21e44bde3 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy@@ -212,6 +212,8 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTraitwhen: "the enabled rule definition for customer B is disabled"conditions = new PollingConditions(timeout: 10)+ // TODO: If we don't do this then test will fail+ rulesDefinition = rulesStorageService.findById(TenantRulesDefinition.class, managerDemoSetup.customerBRulesDefinitionId)rulesDefinition.setEnabled(false)rulesStorageService.merge(rulesDefinition)diff --git a/model/src/main/java/org/openremote/model/Attribute.java b/model/src/main/java/org/openremote/model/Attribute.javaindex 71b2a9acc..1e2c7be9a 100644--- a/model/src/main/java/org/openremote/model/Attribute.java+++ b/model/src/main/java/org/openremote/model/Attribute.java@@ -140,6 +140,7 @@ public class Attribute extends AbstractValueTimestampHolder<Attribute> {return getName() != null && getName().length() > 0 && getType() != null;}+ // TODO: This needs to go into AssetAttribute - bit weird herepublic AttributeRef getAttributeRef(String entityId) {return new AttributeRef(entityId, getName());}