Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Rules exception handling and fact deployment

Rich Turneraa8cb4033c8a
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.java
index ede203801..e0c5053cf 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
@@ -36,6 +36,7 @@ import org.kie.api.runtime.conf.ClockTypeOption;
import org.kie.api.runtime.conf.TimedRuleExectionOption;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.time.SessionClock;
+import org.kie.internal.command.CommandFactory;
import org.openremote.container.util.Util;
import org.openremote.manager.server.asset.AssetProcessingService;
import org.openremote.manager.server.asset.AssetStorageService;
@@ -81,7 +82,7 @@ public class RulesDeployment<T extends Ruleset> {
// 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 boolean error;
+ protected Throwable error;
protected boolean running;
protected long currentFactCount;
final protected Map<AssetUpdate, FactHandle> facts = new HashMap<>();
@@ -115,6 +116,10 @@ public class RulesDeployment<T extends Ruleset> {
}
public boolean isError() {
+ return error != null;
+ }
+
+ public Throwable getError() {
return error;
}
@@ -212,15 +217,15 @@ public class RulesDeployment<T extends Ruleset> {
LOG.info("Added ruleset: " + ruleset);
addSuccessful = true;
}
- } catch (Throwable t) {
- LOG.log(Level.SEVERE, "Error in ruleset: " + ruleset, t);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Error in ruleset: " + ruleset, e);
+ error = e;
// If compilation failed, remove rules from FileSystem so it won't fail on next pass here if any
kfs.delete("src/main/resources/" + ruleset.getId());
}
if (!addSuccessful) {
- // Prevent knowledge session from running again
- error = true;
+ error = new RuntimeException("Ruleset contains an error: " + ruleset);
// Update status of each ruleset
rulesets.forEach((id, rd) -> {
@@ -269,9 +274,8 @@ public class RulesDeployment<T extends Ruleset> {
.stream()
.anyMatch(rd -> rd.getDeploymentStatus() == Ruleset.DeploymentStatus.FAILED);
- error = anyFailed;
-
if (!anyFailed) {
+ error = null;
rulesets.forEach((id, rd) -> {
if (rd.getDeploymentStatus() == Ruleset.DeploymentStatus.READY) {
rd.setDeploymentStatus(Ruleset.DeploymentStatus.DEPLOYED);
@@ -335,9 +339,9 @@ public class RulesDeployment<T extends Ruleset> {
// Use this option to ensure timer rules are fired even in passive mode (triggered by fireAllRules.
// This ensures compatibility with the behaviour of previously used Drools 5.1
kieSessionConfiguration.setOption(TimedRuleExectionOption.YES);
-
try {
knowledgeSession = kieContainer.newKieSession(kieSessionConfiguration);
+ running = true;
setGlobal("assets", createAssetsFacade());
setGlobal("LOG", LOG);
@@ -346,17 +350,17 @@ public class RulesDeployment<T extends Ruleset> {
setGlobal("util", UTIL);
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);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Failed to create the rules engine session", e);
+ error = e;
+ stop();
+ throw e;
}
- running = true;
+ // Insert all the facts into the session
+ List<AssetUpdate> factEntries = new ArrayList<>(facts.keySet());
+ factEntries.forEach(factEntry -> insertFactIntoSession(factEntry, true));
+
LOG.info("Rule engine started");
knowledgeSession.fireAllRules();
}
@@ -374,17 +378,21 @@ public class RulesDeployment<T extends Ruleset> {
LOG.fine("Knowledge session disposed");
}
- facts.clear();
running = false;
}
- protected synchronized void insertFact(AssetUpdate assetUpdate) {
+ protected synchronized void insertFact(AssetUpdate assetUpdate, boolean silent) {
// 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);
+
+ if (isRunning()) {
+ insertFactIntoSession(assetUpdate, silent);
+ } else {
+ facts.put(assetUpdate, null);
+ }
}
}
@@ -393,7 +401,7 @@ public class RulesDeployment<T extends Ruleset> {
// If there already is a fact in working memory for this attribute then delete it
AssetUpdate update = facts.keySet()
.stream()
- .filter(au -> au.getId().equals(assetUpdate.getId()) && au.getAttributeName().equals(assetUpdate.getAttributeName()))
+ .filter(au -> au.attributeRefsEqual(assetUpdate))
.findFirst()
.orElse(null);
@@ -402,7 +410,7 @@ public class RulesDeployment<T extends Ruleset> {
if (factHandle != null) {
facts.remove(update);
- if (knowledgeSession != null) {
+ if (isRunning()) {
try {
// ... retract it from working memory ...
LOG.finest("Removed stale fact '" + update + "' in: " + this);
@@ -417,31 +425,40 @@ public class RulesDeployment<T extends Ruleset> {
}
}
- protected FactHandle insertFactIntoSession(AssetUpdate assetUpdate) {
+ protected FactHandle insertFactIntoSession(AssetUpdate assetUpdate, boolean silent) {
FactHandle factHandle = null;
- if (!isError() && isRunning()) {
- long newFactCount;
- factHandle = knowledgeSession.insert(assetUpdate);
- facts.put(assetUpdate, factHandle);
- LOG.finest("Inserting fact '" + assetUpdate+ "' in: " + this);
-
- 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);
- }
+ if (isRunning()) {
+ try {
+ long newFactCount;
+ factHandle = knowledgeSession.insert(assetUpdate);
+ facts.put(assetUpdate, factHandle);
+ LOG.finest("Inserting fact '" + assetUpdate + "' in: " + this);
+ LOG.finest("On " + this + ", firing all rules");
+// int fireCount = knowledgeSession.fireAllRules();
+ FactHandle finalFactHandle = factHandle;
+ int fireCount = knowledgeSession.fireAllRules((match) -> !silent || !match.getFactHandles().contains(finalFactHandle));
+ 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;
+
+ } catch (Exception e) {
+ // We can end up here because of errors in rule RHS - bubble up the cause
+ error = e;
+ stop();
+ throw new RuntimeException(e);
+ }
} else {
LOG.fine("Engine is in error state or not running (" + toString() + "), ignoring: " + assetUpdate);
}
@@ -533,7 +550,7 @@ public class RulesDeployment<T extends Ruleset> {
};
}
- protected String getRulesetDebug() {
+ protected synchronized String getRulesetDebug() {
return Arrays.toString(rulesets.values().stream().map(rd ->
rd.getClass().getSimpleName()
+ " - "
@@ -544,7 +561,7 @@ public class RulesDeployment<T extends Ruleset> {
}
@Override
- public synchronized String toString() {
+ public String toString() {
return getClass().getSimpleName() + "{" +
"id='" + id + '\'' +
", running='" + running + '\'' +
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.java
index f47317a4f..e31f19c9c 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
@@ -38,12 +38,13 @@ import org.openremote.manager.shared.rules.Ruleset;
import org.openremote.manager.shared.rules.TenantRuleset;
import org.openremote.manager.shared.security.Tenant;
import org.openremote.model.AbstractValueTimestampHolder;
+import org.openremote.model.Attribute;
import org.openremote.model.asset.*;
import org.openremote.model.util.JsonUtil;
import java.util.*;
+import java.util.function.BiFunction;
import java.util.function.Consumer;
-import java.util.function.Function;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@@ -72,6 +73,10 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected final Map<String, RulesDeployment<TenantRuleset>> tenantDeployments = new HashMap<>();
protected final Map<String, RulesDeployment<AssetRuleset>> assetDeployments = new HashMap<>();
protected String[] activeTenantIds;
+ // Keep global list of asset updates that have been pushed to any engines
+ // The objects are already in memory inside the rule engines but keeping them
+ // here means we can quickly insert facts into newly started engines
+ protected List<AssetUpdate> facts = new ArrayList<>();
@Override
public void init(Container container) throws Exception {
@@ -109,116 +114,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
.process(exchange -> {
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
final ServerAsset eventAsset = (ServerAsset) persistenceEvent.getEntity();
-
- // We must load the asset from database (only when required), as the
- // persistence event might not contain a completely loaded asset
- Function<AssetAttribute, AssetUpdate> buildUpdateFunction = new Function<AssetAttribute, AssetUpdate>() {
- final Asset loadedAsset = assetStorageService.find(eventAsset.getId(), true);
-
- @Override
- public AssetUpdate apply(AssetAttribute attribute) {
- return new AssetUpdate(loadedAsset,
- new AssetAttribute(loadedAsset.getId(),
- attribute.getName(),
- attribute.getJsonObject())
- );
- }
- };
-
- switch (persistenceEvent.getCause()) {
- case INSERT:
- // New asset has been created so get attributes that have RULES_FACT meta
- AssetAttributes addedAttributes = new AssetAttributes(eventAsset);
-
- addedAttributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .forEach(attribute -> {
- AssetUpdate update = buildUpdateFunction.apply(attribute);
- // Set the status to completed already so rules cannot interfere with this initial insert
- update.setStatus(AssetUpdate.Status.COMPLETED);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
- insertFact(update, true);
- });
- break;
- case UPDATE:
-
- int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
- if (attributesIndex >= 0) {
- // Attributes have possibly changed so need to compare old and new state to determine
- // which facts to retract and which to insert
- AssetAttributes oldAttributes = new AssetAttributes((JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);
- AssetAttributes newAttributes = new AssetAttributes((JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);
-
- List<AssetAttribute> oldFactAttributes = oldAttributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .collect(Collectors.toList());
-
- List<AssetAttribute> newFactAttributes = newAttributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .collect(Collectors.toList());
-
- // Compare attributes by JSON value
- // Retract facts for attributes that are in oldFactAttributes but not in newFactAttributes
-
- oldFactAttributes
- .stream()
- .filter(oldFactAttribute -> newFactAttributes
- .stream()
- .noneMatch(newFactAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison
- oldFactAttribute.getJsonObject(),
- newFactAttribute.getJsonObject(),
- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
- )
- )
- .forEach(obsoleteFactAttribute -> {
- AssetUpdate update = buildUpdateFunction.apply(obsoleteFactAttribute);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + update);
- retractFact(update);
- });
-
- // Insert facts for attributes that are in newFactAttributes but not in oldFactAttributes
- newFactAttributes
- .stream()
- .filter(newFactAttribute -> oldFactAttributes
- .stream()
- .noneMatch(oldFactAttribute ->
- JsonUtil.equals( // Ignore the timestamp in comparison
- oldFactAttribute.getJsonObject(),
- newFactAttribute.getJsonObject(),
- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)
- )
- )
- )
- .forEach(newFactAttribute -> {
- AssetUpdate update = buildUpdateFunction.apply(newFactAttribute);
- // Set the status to completed already so rules cannot interfere with this initial insert
- update.setStatus(AssetUpdate.Status.COMPLETED);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
- insertFact(update, true);
- });
- }
- break;
- case DELETE:
- // Retract any facts that were associated with this asset
- AssetAttributes removedAttributes = new AssetAttributes(eventAsset);
- removedAttributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .forEach(attribute -> {
- // We can't load the asset again (it was deleted), so don't use buildUpdateFunction() and
- // hope that the path of the event asset has been loaded before deletion
- AssetUpdate update = new AssetUpdate(eventAsset, attribute);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + update);
- retractFact(update);
- });
- break;
- }
+ processAssetChange(eventAsset, persistenceEvent);
});
}
@Override
public void start(Container container) throws Exception {
LOG.info("Deploying global rulesets");
- rulesetStorageService.findEnabledGlobalRulesets().forEach(this::deployGlobalRuleset);
+ rulesetStorageService.findEnabledGlobalRulesets().forEach(this::insertGlobalRuleset);
LOG.info("Deploying tenant rulesets");
activeTenantIds = identityService.getActiveTenantIds();
@@ -227,34 +130,29 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
.filter(rd ->
Arrays.stream(activeTenantIds)
.anyMatch(tenantId -> rd.getRealmId().equals(tenantId))
- ).forEach(this::deployTenantRuleset);
+ ).forEach(this::insertTenantRuleset);
LOG.info("Deploying asset rulesets");
// Group by asset ID then tenant and check tenant is enabled
- deployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets());
+ insertAssetRulesets(rulesetStorageService.findEnabledAssetRulesets());
LOG.info("Loading all assets with fact attributes to initialize state of rules engines");
- List<ServerAsset> assets = assetStorageService.findAll(
- new AssetQuery()
- .select(new AssetQuery.Select(true))
- .attributeMeta(
- new AssetQuery.AttributeMetaPredicate(
- AssetMeta.RULES_FACT,
- new AssetQuery.BooleanPredicate(true))
- ));
-
- assets.forEach(asset -> {
- AssetAttributes attributes = new AssetAttributes(asset);
- attributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .forEach(attribute -> {
- AssetUpdate update = new AssetUpdate(asset, attribute);
- // Set the status to completed already so rules cannot interfere with this initial insert
- update.setStatus(AssetUpdate.Status.COMPLETED);
- LOG.fine("Inserting initial rules engine state: " + update);
- insertFact(update, true);
+ List<Pair<ServerAsset, List<AssetAttribute>>> assetRuleAttributesList = findRuleAttributes(null, null);
+
+ // Push each rule attribute as an asset update through the rule engine chain
+ // that will ensure the insert only happens to the engines in scope
+ assetRuleAttributesList
+ .forEach(assetRuleAttributes -> {
+ ServerAsset asset = assetRuleAttributes.key;
+ List<AssetAttribute> ruleAttributes = assetRuleAttributes.value;
+ ruleAttributes.forEach(ruleAttribute -> {
+ AssetUpdate update = new AssetUpdate(asset, ruleAttribute);
+ // Set the status to completed already so rules cannot interfere with this initial insert
+ update.setStatus(AssetUpdate.Status.COMPLETED);
+ LOG.fine("Inserting initial rules engine state: " + update);
+ insertFact(update, true);
+ });
});
- });
}
@Override
@@ -284,7 +182,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
}
- public synchronized void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {
+ protected synchronized void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {
// Check if enabled status has changed
boolean wasEnabled = Arrays.asList(activeTenantIds).contains(tenant.getId());
boolean isEnabled = tenant.getEnabled() && cause != PersistenceEvent.Cause.DELETE;
@@ -313,14 +211,117 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Insert tenant deployment for this tenant if it has any rulesets
rulesetStorageService
.findEnabledTenantRulesets(tenant.getId())
- .forEach(this::deployTenantRuleset);
+ .forEach(this::insertTenantRuleset);
// Insert any asset deployments for assets in this realm that have rulesets
- deployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets(tenant.getId()));
+ insertAssetRulesets(rulesetStorageService.findEnabledAssetRulesets(tenant.getId()));
+ }
+ }
+
+ protected synchronized void processAssetChange(ServerAsset asset, PersistenceEvent persistenceEvent) {
+
+ // We must load the asset from database (only when required), as the
+ // persistence event might not contain a completely loaded asset
+ BiFunction<String, AssetAttribute, AssetUpdate> buildUpdateFunction = (assetId, attribute) -> {
+ final Asset loadedAsset = assetStorageService.find(assetId, true);
+ return new AssetUpdate(loadedAsset,
+ new AssetAttribute(loadedAsset.getId(),
+ attribute.getName(),
+ attribute.getJsonObject()));
+ };
+
+ switch (persistenceEvent.getCause()) {
+ case INSERT:
+
+ // New asset has been created so get attributes that have RULES_FACT meta
+ AssetAttributes addedAttributes = new AssetAttributes(asset);
+
+ addedAttributes.get().stream()
+ .filter(AssetAttribute::isRulesFact)
+ .forEach(attribute -> {
+ AssetUpdate update = buildUpdateFunction.apply(asset.getId(), attribute);
+ // Set the status to completed already so rules cannot interfere with this initial insert
+ update.setStatus(AssetUpdate.Status.COMPLETED);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
+ insertFact(update, true);
+ });
+ break;
+
+ case UPDATE:
+
+ int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
+ if (attributesIndex >= 0) {
+ // Attributes have possibly changed so need to compare old and new state to determine
+ // which facts to retract and which to insert
+ AssetAttributes oldAttributes = new AssetAttributes((JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);
+ AssetAttributes newAttributes = new AssetAttributes((JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);
+
+ List<AssetAttribute> oldFactAttributes = oldAttributes.get().stream()
+ .filter(AssetAttribute::isRulesFact)
+ .collect(Collectors.toList());
+
+ List<AssetAttribute> newFactAttributes = newAttributes.get().stream()
+ .filter(AssetAttribute::isRulesFact)
+ .collect(Collectors.toList());
+
+ // Compare attributes by JSON value
+ // Retract facts for attributes that are in oldFactAttributes but not in newFactAttributes
+
+ oldFactAttributes
+ .stream()
+ .filter(oldFactAttribute -> newFactAttributes
+ .stream()
+ .noneMatch(newFactAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison
+ oldFactAttribute.getJsonObject(),
+ newFactAttribute.getJsonObject(),
+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
+ )
+ )
+ .forEach(obsoleteFactAttribute -> {
+ AssetUpdate update = buildUpdateFunction.apply(asset.getId(), obsoleteFactAttribute);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + update);
+ retractFact(update);
+ });
+
+ // Insert facts for attributes that are in newFactAttributes but not in oldFactAttributes
+ newFactAttributes
+ .stream()
+ .filter(newFactAttribute -> oldFactAttributes
+ .stream()
+ .noneMatch(oldFactAttribute ->
+ JsonUtil.equals( // Ignore the timestamp in comparison
+ oldFactAttribute.getJsonObject(),
+ newFactAttribute.getJsonObject(),
+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)
+ )
+ )
+ )
+ .forEach(newFactAttribute -> {
+ AssetUpdate update = buildUpdateFunction.apply(asset.getId(), newFactAttribute);
+ // Set the status to completed already so rules cannot interfere with this initial insert
+ update.setStatus(AssetUpdate.Status.COMPLETED);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
+ insertFact(update, true);
+ });
+ }
+ break;
+ case DELETE:
+ // Retract any facts that were associated with this asset
+ AssetAttributes removedAttributes = new AssetAttributes(asset);
+ removedAttributes.get().stream()
+ .filter(AssetAttribute::isRulesFact)
+ .forEach(attribute -> {
+ // We can't load the asset again (it was deleted), so don't use buildUpdateFunction() and
+ // hope that the path of the event asset has been loaded before deletion
+ AssetUpdate update = new AssetUpdate(asset, attribute);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + update);
+ retractFact(update);
+ });
+ break;
}
}
- protected void processRulesetChange(Ruleset ruleset, PersistenceEvent.Cause cause) {
+ protected synchronized void processRulesetChange(Ruleset ruleset, PersistenceEvent.Cause cause) {
if (cause == PersistenceEvent.Cause.DELETE || !ruleset.isEnabled()) {
if (ruleset instanceof GlobalRuleset) {
retractGlobalRuleset((GlobalRuleset) ruleset);
@@ -331,24 +332,54 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
} else {
if (ruleset instanceof GlobalRuleset) {
- deployGlobalRuleset((GlobalRuleset) ruleset);
+
+ RulesDeployment newEngine = insertGlobalRuleset((GlobalRuleset)ruleset);
+ if (newEngine != null) {
+ // Push all existing facts into the engine
+ facts.forEach(assetUpdate -> newEngine.insertFact(assetUpdate, true));
+ }
+
} else if (ruleset instanceof TenantRuleset) {
- deployTenantRuleset((TenantRuleset) ruleset);
+
+ RulesDeployment newEngine = insertTenantRuleset((TenantRuleset) ruleset);
+ if (newEngine != null) {
+ // Push all existing facts for this tenant into the engine
+ facts.forEach(assetUpdate -> {
+ if (assetUpdate.getRealmId().equals(((TenantRuleset) ruleset).getRealmId())) {
+ newEngine.insertFact(assetUpdate, true);
+ }
+ });
+ }
+
} else if (ruleset instanceof AssetRuleset) {
+
// Must reload from the database, the ruleset might not be completely hydrated on INSERT or UPDATE
AssetRuleset assetRuleset = rulesetStorageService.findEnabledAssetRuleset(ruleset.getId());
- deployAssetRuleset(assetRuleset);
+ RulesDeployment newEngine = insertAssetRuleset(assetRuleset);
+ if (newEngine != null) {
+ // Push all existing facts for this asset (and it's children into the engine)
+ getFactsInScope(((AssetRuleset) ruleset).getAssetId())
+ .forEach(assetUpdate -> newEngine.insertFact(assetUpdate, true));
+
+ }
}
}
}
- protected synchronized void deployGlobalRuleset(GlobalRuleset ruleset) {
+ /**
+ * Inserts the ruleset into the global engine creating the engine if necessary; if the engine was created then it
+ * is returned from the method.
+ */
+ protected synchronized RulesDeployment<GlobalRuleset> insertGlobalRuleset(GlobalRuleset ruleset) {
+ boolean created = globalDeployment == null;
+
// Global rules have access to everything in the system
if (globalDeployment == null) {
globalDeployment = new RulesDeployment<>(assetStorageService, assetProcessingService, GlobalRuleset.class, "GLOBAL");
}
globalDeployment.insertRuleset(ruleset);
+ return created ? globalDeployment : null;
}
protected synchronized void retractGlobalRuleset(GlobalRuleset ruleset) {
@@ -363,14 +394,19 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
}
- protected synchronized void deployTenantRuleset(TenantRuleset ruleset) {
+ protected synchronized RulesDeployment<TenantRuleset> insertTenantRuleset(TenantRuleset ruleset) {
+ final boolean[] created = {false};
+
// Look for existing deployment for this tenant
RulesDeployment<TenantRuleset> deployment = tenantDeployments
- .computeIfAbsent(ruleset.getRealmId(), (realmId) ->
- new RulesDeployment<>(assetStorageService, assetProcessingService, TenantRuleset.class, realmId)
- );
+ .computeIfAbsent(ruleset.getRealmId(), (realmId) -> {
+ created[0] = true;
+ return new RulesDeployment<>(assetStorageService, assetProcessingService, TenantRuleset.class, realmId);
+ });
deployment.insertRuleset(ruleset);
+
+ return created[0] ? deployment : null;
}
protected synchronized void retractTenantRuleset(TenantRuleset ruleset) {
@@ -386,7 +422,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
}
- protected void deployAssetRulesets(List<AssetRuleset> rulesets) {
+ protected void insertAssetRulesets(List<AssetRuleset> rulesets) {
rulesets
.stream()
.collect(Collectors.groupingBy(AssetRuleset::getAssetId))
@@ -410,18 +446,22 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
tenantAssetAndRules.stream()
//.sorted(Comparator.comparingInt(item -> item.key.getPath().length))
.flatMap(assetAndRules -> assetAndRules.value.stream())
- .forEach(this::deployAssetRuleset);
+ .forEach(this::insertAssetRuleset);
});
}
- protected void deployAssetRuleset(AssetRuleset ruleset) {
+ protected synchronized RulesDeployment<AssetRuleset> insertAssetRuleset(AssetRuleset ruleset) {
+ final boolean[] created = {false};
+
// Look for existing deployment for this asset
RulesDeployment<AssetRuleset> deployment = assetDeployments
- .computeIfAbsent(ruleset.getAssetId(), (assetId) ->
- new RulesDeployment<>(assetStorageService, assetProcessingService, AssetRuleset.class, assetId)
- );
+ .computeIfAbsent(ruleset.getAssetId(), (assetId) -> {
+ created[0] = true;
+ return new RulesDeployment<>(assetStorageService, assetProcessingService, AssetRuleset.class, assetId);
+ });
deployment.insertRuleset(ruleset);
+ return created[0] ? deployment : null;
}
protected synchronized void retractAssetRuleset(AssetRuleset ruleset) {
@@ -437,20 +477,39 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
}
- // 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, boolean skipStatusCheck) {
// TODO: implement rules processing error state handling
// Get the chain of rule engines that we need to pass through
- List<RulesDeployment> rulesDeployments = getEnginesInScope(assetUpdate.getRealmId(), assetUpdate.getPath());
+ List<RulesDeployment> rulesDeployments = getEnginesInScope(assetUpdate.getRealmId(), assetUpdate.getPathFromRoot());
if (rulesDeployments.size() == 0) {
LOG.fine("Ignoring asset update as there are no matching rules deployments: " + assetUpdate);
}
+ if (!skipStatusCheck) {
+ // Check that all engines in the scope are not in ERROR state
+ if (rulesDeployments.stream().anyMatch(rd -> rd.isError())) {
+ LOG.severe("At least one rule engine is in an error state so cannot process update:" + assetUpdate);
+ assetUpdate.setStatus(AssetUpdate.Status.ERROR);
+ return;
+ }
+ }
+
+ // Remove any stale fact that has equality with this new one or the attribute ref matches
+ // (this is what rules deployment does also)
+ if (!facts.remove(assetUpdate)) {
+ facts.removeIf(storedUpdate -> storedUpdate.attributeRefsEqual(assetUpdate));
+ }
+ // Insert the new fact
+ facts.add(assetUpdate);
+
// Pass through each engine and try and insert the fact
for (RulesDeployment deployment : rulesDeployments) {
- deployment.insertFact(assetUpdate);
+
+ // Any exceptions in rule RHS will bubble up and the engine would be marked as in ERROR so future
+ // updates will be blocked
+ deployment.insertFact(assetUpdate, skipStatusCheck);
if (!skipStatusCheck) {
// We have to check status between each engine insert as a rule in the engine could have updated
@@ -468,7 +527,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected void retractFact(AssetUpdate assetUpdate) {
// Get the chain of rule engines that we need to pass through
- List<RulesDeployment> rulesDeployments = getEnginesInScope(assetUpdate.getRealmId(), assetUpdate.getPath());
+ List<RulesDeployment> rulesDeployments = getEnginesInScope(assetUpdate.getRealmId(), assetUpdate.getPathFromRoot());
+
+ if (!facts.remove(assetUpdate)) {
+ facts.removeIf(storedUpdate -> storedUpdate.attributeRefsEqual(assetUpdate));
+ }
if (rulesDeployments.size() == 0) {
LOG.fine("Ignoring asset update as there are no matching rules deployments: " + assetUpdate);
@@ -480,10 +543,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
}
- protected List<RulesDeployment> getEnginesInScope(String assetRealmId, String[] assetPath) {
- // We need to reverse the asset path to start from the top down
- assetPath = Util.reverseArray(assetPath, String.class);
+ protected List<AssetUpdate> getFactsInScope(String assetId) {
+ return facts
+ .stream()
+ .filter(assetUpdate -> Arrays.asList(assetUpdate.getPathFromRoot()).contains(assetId))
+ .collect(Collectors.toList());
+ }
+ protected List<RulesDeployment> getEnginesInScope(String assetRealmId, String[] assetPath) {
List<RulesDeployment> rulesDeployments = new ArrayList<>();
// Add global engine (if it exists)
@@ -510,6 +577,27 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
return rulesDeployments;
}
+ protected List<Pair<ServerAsset, List<AssetAttribute>>> findRuleAttributes(AssetQuery.TenantPredicate tenantPredicate, AssetQuery.ParentPredicate parentPredicate) {
+ List<ServerAsset> assets = assetStorageService.findAll(
+ new AssetQuery()
+ .select(new AssetQuery.Select(true))
+ .parent(parentPredicate)
+ .tenant(tenantPredicate)
+ .attributeMeta(
+ new AssetQuery.AttributeMetaPredicate(
+ AssetMeta.RULES_FACT,
+ new AssetQuery.BooleanPredicate(true))
+ ));
+
+ return assets.stream().map(asset -> {
+ AssetAttributes attributes = new AssetAttributes(asset);
+ List<AssetAttribute> ruleAttributes = attributes.get().stream()
+ .filter(AssetAttribute::isRulesFact).collect(Collectors.toList());
+ return new Pair<>(asset, ruleAttributes);
+
+ }).collect(Collectors.toList());
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{}";
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
index d81d355fd..5aa435679 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
@@ -4,6 +4,7 @@ import elemental.json.Json
import org.openremote.agent3.protocol.AbstractProtocol
import org.openremote.manager.server.asset.AssetProcessingService
import org.openremote.manager.server.asset.AssetStorageService
+import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.asset.ServerAsset
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup
@@ -93,12 +94,29 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
def container = startContainer(defaultConfig(serverPort), defaultServices(mockProtocol))
def assetStorageService = container.getService(AssetStorageService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
+ def rulesService = container.getService(RulesService.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
assetProcessingService.processors.add(0, mockStartConsumer)
assetProcessingService.processors.add(mockEndConsumer)
//endregion
+ // The conditions here depend on how we handle the initial insert of facts into the rule engines
+ //expect: "the demo rule engine should start and trigger the 'Switch room lights off when apartment ALL LIGHTS OFF switch is off' rule and cause attribute events to go through the system"
+ expect: "the demo rule engine should start and trigger the 'Switch room lights off when apartment ALL LIGHTS OFF switch is off' rule and cause attribute events to go through the system"
+ conditions.eventually {
+ def customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
+ assert customerAEngine != null
+ assert customerAEngine.isRunning()
+ assert customerAEngine.rulesets.size() == 1
+ assert updatesPassedStartOfProcessingChain.size() == 0
+ assert updatesReachedEndOfProcessingChain.size() == 0
+ }
+
+ when: "the processing chain counters are reset"
+ updatesPassedStartOfProcessingChain.clear()
+ updatesReachedEndOfProcessingChain.clear()
+
//region and: "a mock agent that uses the mock protocol is created"
and: "a mock agent that uses the mock protocol is created"
def mockAgent = new ServerAsset()
@@ -157,7 +175,8 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
mockThing = assetStorageService.merge(mockThing)
//endregion
- expect: "the mock thing to be deployed to the protocol"
+
+ then: "the mock thing to be deployed to the protocol"
conditions.eventually {
assert protocolDeployed
}
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
index 2be983b77..9cc2abc8f 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
@@ -3,6 +3,7 @@ package org.openremote.test.rules
import elemental.json.Json
import org.openremote.manager.server.asset.AssetProcessingService
import org.openremote.manager.server.asset.AssetStorageService
+import org.openremote.manager.server.rules.RulesDeployment
import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup
@@ -29,21 +30,20 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
def rulesService = container.getService(RulesService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
def assetStorageService = container.getService(AssetStorageService.class)
+ RulesDeployment customerAEngine
expect: "the rule engines to become available and be running"
conditions.eventually {
- def customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
+ customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.isRunning()
- assert customerAEngine.allRulesets.find { it.id == rulesDemoSetup.apartmentActionsRulesetId } != null
}
- /* TODO This is broken, loading facts on startup is not done
and: "the demo attributes marked with RULES_FACT = true meta should be inserted into the engines"
conditions.eventually {
- assert globalEngine.facts.size() == 11
+ assert rulesService.facts.size() == 8
+ assert customerAEngine.facts.size() == 8
}
- */
and: "the room lights in an apartment to be on"
def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
index 76ab5c5cc..d1241ef1f 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
@@ -25,7 +25,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
def "Check basic rules engine deployment"() {
given: "expected conditions"
- def conditions = new PollingConditions(timeout: 5)
+ def conditions = new PollingConditions(timeout: 10)
and: "the container is started"
def serverPort = findEphemeralPort()
@@ -235,7 +235,8 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
conditions.eventually {
assert rulesService.globalDeployment.allRulesets.length == 3
assert rulesService.globalDeployment.running == false
- assert rulesService.globalDeployment.error == true
+ assert rulesService.globalDeployment.isError()
+ assert rulesService.globalDeployment.error instanceof RuntimeException
assert rulesService.globalDeployment.allRulesets[0].enabled
assert rulesService.globalDeployment.allRulesets[0].name == "Some global demo rules"
assert rulesService.globalDeployment.allRulesets[0].deploymentStatus == DeploymentStatus.READY
@@ -254,7 +255,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
conditions.eventually {
assert rulesService.globalDeployment.allRulesets.length == 2
assert rulesService.globalDeployment.running == true
- assert rulesService.globalDeployment.error == false
+ assert rulesService.globalDeployment.isError() == false
assert rulesService.globalDeployment.allRulesets[0].enabled
assert rulesService.globalDeployment.allRulesets[0].name == "Some global demo rules"
assert rulesService.globalDeployment.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
index 8ee563f7d..15c8c8cbe 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
@@ -30,13 +30,14 @@ import static org.openremote.test.RulesTestUtil.attachRuleExecutionLogger
class BasicRulesProcessingTest extends Specification implements ManagerContainerTrait {
- RulesDeployment globalEngine, masterEngine, customerAEngine, smartHomeEngine, apartment1Engine, apartment3Engine
+ RulesDeployment globalEngine, masterEngine, customerAEngine, smartHomeEngine, apartment1Engine, apartment2Engine, apartment3Engine
List<String> globalEngineFiredRules = []
List<String> masterEngineFiredRules = []
List<String> customerAEngineFiredRules = []
List<String> smartHomeEngineFiredRules = []
List<String> apartment1EngineFiredRules = []
+ List<String> apartment2EngineFiredRules = []
List<String> apartment3EngineFiredRules = []
def resetRuleExecutionLoggers() {
@@ -44,6 +45,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
customerAEngineFiredRules.clear()
smartHomeEngineFiredRules.clear()
apartment1EngineFiredRules.clear()
+ apartment2EngineFiredRules.clear()
apartment3EngineFiredRules.clear()
}
@@ -53,6 +55,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
assert customerAEngineFiredRules.size() == 0
assert smartHomeEngineFiredRules.size() == 0
assert apartment1EngineFiredRules.size() == 0
+ assert apartment2EngineFiredRules.size() == 0
assert apartment3EngineFiredRules.size() == 0
}
@@ -90,17 +93,22 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
apartment1Engine = rulesService.assetDeployments.get(managerDemoSetup.apartment1Id)
assert apartment1Engine != null
assert apartment1Engine.isRunning()
+ apartment2Engine = rulesService.assetDeployments.get(managerDemoSetup.apartment2Id)
+ assert apartment2Engine == null
apartment3Engine = rulesService.assetDeployments.get(managerDemoSetup.apartment3Id)
assert apartment3Engine != null
assert apartment3Engine.isRunning()
}
- /* TODO This is broken, loading facts on startup is not done
and: "the demo attributes marked with RULES_FACT = true meta should be inserted into the engines"
conditions.eventually {
- assert globalEngine.facts.size() == 11
+ assert rulesService.facts.size() == 8
+ assert globalEngine.facts.size() == 8
+ assert masterEngine.facts.size() == 0
+ assert customerAEngine.facts.size() == 8
+ assert apartment1Engine.facts.size() == 4
+ assert apartment3Engine.facts.size() == 2
}
- */
when: "rule execution loggers are attached to the engines"
attachRuleExecutionLogger(globalEngine, globalEngineFiredRules)
@@ -185,11 +193,12 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
)
rulesetStorageService.merge(assetRuleset)
- then: "the smart home rule engine should have ben created, loaded the new rule definition and started"
+ then: "the smart home rule engine should have ben created, loaded the new rule definition and facts and started"
conditions.eventually {
smartHomeEngine = rulesService.assetDeployments.get(managerDemoSetup.smartHomeId)
assert smartHomeEngine != null
assert smartHomeEngine.isRunning()
+ assert smartHomeEngine.facts.size() == 8
assert smartHomeEngine.allRulesets.length == 1
assert smartHomeEngine.allRulesets[0].enabled
assert smartHomeEngine.allRulesets[0].name == "Some smart home asset rules"
@@ -258,6 +267,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
globalEngine = rulesService.globalDeployment
assert globalEngine != null
assert globalEngine.isRunning()
+ assert globalEngine.facts.size() == 8
assert globalEngine.allRulesets.length == 2
assert globalEngine.allRulesets[1].enabled
assert globalEngine.allRulesets[1].name == "Some global test rules"
@@ -322,16 +332,19 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
asset.setAttributes(attributes.getJsonObject())
asset = assetStorageService.merge(asset)
- then: "the engines in scope should have fired the matched rules (Kitchen All should fire)"
+ then: "after a few seconds the engines in scope should not have fired any rules but the facts should have been inserted"
conditions.eventually {
- assert globalEngineFiredRules.size() == 2
- assert globalEngineFiredRules.containsAll(["All", "All changed"])
- assert customerAEngineFiredRules.size() == 2
- assert customerAEngineFiredRules.containsAll(["All", "All changed"])
- assert smartHomeEngineFiredRules.size() == 4
- assert smartHomeEngineFiredRules.containsAll(["Kitchen All", "Parent Type Residence", "Asset Type Room", "String Attributes"])
- assert apartment1EngineFiredRules.size() == 2
- assert apartment1EngineFiredRules.containsAll(["All", "All changed"])
+ assert rulesService.facts.size() == 9
+ assert globalEngine.facts.size() == 9
+ assert masterEngine.facts.size() == 0
+ assert customerAEngine.facts.size() == 9
+ assert smartHomeEngine.facts.size() == 9
+ assert apartment1Engine.facts.size() == 5
+ assert apartment3Engine.facts.size() == 2
+ assert globalEngineFiredRules.size() == 0
+ assert customerAEngineFiredRules.size() == 0
+ assert smartHomeEngineFiredRules.size() == 0
+ assert apartment1EngineFiredRules.size() == 0
assert apartment3EngineFiredRules.size() == 0
}
@@ -347,12 +360,22 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
new AssetAttribute("testInteger", AttributeType.INTEGER, Json.create(0))
)
asset.setAttributes(attributes.getJsonObject())
- def factCount = smartHomeEngine.facts.size()
asset = assetStorageService.merge(asset)
- then: "after a few seconds the fact count shouldn't change"
+ then: "after a few seconds the fact count shouldn't change and no rules should have fired"
new PollingConditions(initialDelay: 3).eventually {
- assert smartHomeEngine.facts.size() == factCount
+ assert rulesService.facts.size() == 9
+ assert globalEngine.facts.size() == 9
+ assert masterEngine.facts.size() == 0
+ assert customerAEngine.facts.size() == 9
+ assert smartHomeEngine.facts.size() == 9
+ assert apartment1Engine.facts.size() == 5
+ assert apartment3Engine.facts.size() == 2
+ assert globalEngineFiredRules.size() == 0
+ assert customerAEngineFiredRules.size() == 0
+ assert smartHomeEngineFiredRules.size() == 0
+ assert apartment1EngineFiredRules.size() == 0
+ assert apartment3EngineFiredRules.size() == 0
}
when: "the Kitchen room asset is modified to set the RULES_FACT to false"
@@ -366,12 +389,22 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
new AssetAttribute("testInteger", AttributeType.INTEGER, Json.create(0))
)
asset.setAttributes(attributes.getJsonObject())
- factCount = smartHomeEngine.facts.size()
asset = assetStorageService.merge(asset)
- then: "the facts should be removed from the rule engines"
+ then: "the facts should be removed from the rule engines and no rules should have fired"
conditions.eventually {
- assert smartHomeEngine.facts.size() == factCount - 1
+ assert rulesService.facts.size() == 8
+ assert globalEngine.facts.size() == 8
+ assert masterEngine.facts.size() == 0
+ assert customerAEngine.facts.size() == 8
+ assert smartHomeEngine.facts.size() == 8
+ assert apartment1Engine.facts.size() == 4
+ assert apartment3Engine.facts.size() == 2
+ assert globalEngineFiredRules.size() == 0
+ assert customerAEngineFiredRules.size() == 0
+ assert smartHomeEngineFiredRules.size() == 0
+ assert apartment1EngineFiredRules.size() == 0
+ assert apartment3EngineFiredRules.size() == 0
}
when: "the Kitchen room asset is modified to set all attributes to RULES_FACT = true"
@@ -392,27 +425,40 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
asset.setAttributes(attributes.getJsonObject())
asset = assetStorageService.merge(asset)
- then: "the engines in scope should have fired the matched rules twice (Kitchen All should fire twice Kitchen Integer should have fired once)"
+ then: "the facts should be added to the rule engines and no rules should have fired"
conditions.eventually {
- assert globalEngineFiredRules.size() == 4
- assert globalEngineFiredRules.containsAll(["All", "All changed"])
- assert customerAEngineFiredRules.size() == 4
- assert customerAEngineFiredRules.containsAll(["All", "All changed"])
- assert smartHomeEngineFiredRules.size() == 9
- assert smartHomeEngineFiredRules.containsAll(["Kitchen All", "Parent Type Residence", "Asset Type Room", "String Attributes", "Kitchen Integer Attributes"])
- assert apartment1EngineFiredRules.size() == 4
- assert apartment1EngineFiredRules.containsAll(["All", "All changed"])
+ assert rulesService.facts.size() == 10
+ assert globalEngine.facts.size() == 10
+ assert masterEngine.facts.size() == 0
+ assert customerAEngine.facts.size() == 10
+ assert smartHomeEngine.facts.size() == 10
+ assert apartment1Engine.facts.size() == 6
+ assert apartment3Engine.facts.size() == 2
+ assert globalEngineFiredRules.size() == 0
+ assert customerAEngineFiredRules.size() == 0
+ assert smartHomeEngineFiredRules.size() == 0
+ assert apartment1EngineFiredRules.size() == 0
assert apartment3EngineFiredRules.size() == 0
}
when: "the Kitchen room asset is deleted"
resetRuleExecutionLoggers()
- factCount = smartHomeEngine.facts.size()
assetStorageService.delete(asset.getId())
- then: "the facts should be removed from the rule engines"
+ then: "the facts should be removed from the rule engines and no rules should have fired"
conditions.eventually {
- assert smartHomeEngine.facts.size() == factCount - 2
+ assert rulesService.facts.size() == 8
+ assert globalEngine.facts.size() == 8
+ assert masterEngine.facts.size() == 0
+ assert customerAEngine.facts.size() == 8
+ assert smartHomeEngine.facts.size() == 8
+ assert apartment1Engine.facts.size() == 4
+ assert apartment3Engine.facts.size() == 2
+ assert globalEngineFiredRules.size() == 0
+ assert customerAEngineFiredRules.size() == 0
+ assert smartHomeEngineFiredRules.size() == 0
+ assert apartment1EngineFiredRules.size() == 0
+ assert apartment3EngineFiredRules.size() == 0
}
cleanup: "the server should be stopped"
diff --git a/model/src/main/java/org/openremote/model/asset/AssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
index df191abda..695f65819 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
@@ -73,7 +73,7 @@ public class AssetUpdate {
final protected AssetType type;
- final protected String[] path;
+ final protected String[] pathFromRoot;
final protected String parentId;
@@ -111,7 +111,7 @@ public class AssetUpdate {
if (asset.getPath() == null) {
throw new IllegalArgumentException("Asset not loaded completely, empty path: " + asset);
}
- this.path = asset.getPath();
+ this.pathFromRoot = asset.getReversePath(); // This is proving more useful than forward path
this.typeString = asset.getType();
this.type = asset.getWellKnownType();
this.createdOn = asset.getCreatedOn();
@@ -147,9 +147,8 @@ public class AssetUpdate {
return type;
}
-
- public String[] getPath() {
- return path;
+ public String[] getPathFromRoot() {
+ return pathFromRoot;
}
public String getParentId() {
@@ -284,6 +283,19 @@ public class AssetUpdate {
oldValueTimestamp == that.oldValueTimestamp;
}
+ /**
+ * This is here because {@link #getAttribute()} is not always publicly accessible
+ * @param assetUpdate
+ * @return
+ */
+ public boolean attributeRefsEqual(AssetUpdate assetUpdate) {
+ if (assetUpdate == null || assetUpdate.attribute == null) {
+ return false;
+ }
+
+ return assetUpdate.attribute.getAttributeRef().equals(attribute.getAttributeRef());
+ }
+
@Override
public int hashCode() {
return id.hashCode() + getAttributeName().hashCode() + JsonUtil.hashCode(getValue())