Skip to content

armgit / core

Public Imported from GitHub
0

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

Implemented RULES_EVENT processing

Christian Bauer5534eb5f9cc5
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.java
index db4a07875..876e54747 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
@@ -43,23 +43,16 @@ import static org.openremote.agent3.protocol.Protocol.SENSOR_TOPIC;
import static org.openremote.model.asset.AssetType.THING;
/**
- * Process asset attribute changes, routing asset-related messages.
- * <p>
- * Receives {@link AttributeEvent} messages in {@link #updateAttributeValue(AttributeEvent)} and processes them.
- * <p>
- * {@link AttributeEvent} messages can come from various sources:
+ * Receives {@link AttributeEvent}s and processes them.
* <p>
+ * {@link AttributeEvent}s 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>
+ * <li>Protocol ({@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate})</li>
+ * <li>User/Client initiated ({@link #updateAttributeValue})</li>
+ * <li>Rules ({@link org.openremote.model.rules.Assets#dispatch})</li>
* </ul>
- * <p>
- * <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&lt;AssetUpdate&gt;}.
- * <p>
+ * The {@link AttributeEvent}s 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 consumers.
* <p>
* The regular processing chain is:
* <ul>
@@ -68,54 +61,53 @@ import static org.openremote.model.asset.AssetType.THING;
* <li>{@link AssetStorageService}</li>
* <li>{@link AssetDatapointService}</li>
* </ul>
+ * <em>Rules Service processing logic</em>
* <p>
- * <p>
- * Rules Service processing logic:
- * <p>
- * Checks if attribute has {@link org.openremote.model.asset.AssetMeta#RULES_FACT} meta item with value of true and if
+ * Checks if attribute is {@link AssetAttribute#isRulesFact} or {@link AssetAttribute#isRulesEvent}, 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>
- * <p>
- * Agent service processing logic:
+ * engines but it should continue through the processing chain. For {@link org.openremote.model.rules.AssetEvent}
+ * messages, they are inserted in the rules sessions in scope and expired automatically either by a) the rules session
+ * if no time-pattern can possibly match the event timestamp anymore or b) by the rules service if the event lifetime
+ * set in {@link RulesService#RULES_EVENT_EXPIRES} is reached or c) by the rules service if the event lifetime set in
+ * the attribute {@link AssetMeta#RULES_EVENT_EXPIRES} is reached.
* <p>
- * 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.
+ * <em>Agent service processing logic</em>
* <p>
- * 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.
+ * When the attribute event came from a Protocol (i.e. generated by a call from
+ * {@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate} then
+ * the agent service will ignore the message and just pass it onto the next consumer.
* <p>
- * 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)}.
+ * When the attribute event came from any other source then the agent service will check if it relates
+ * to a {@link AssetType#THING} and if so it will check if the attribute is linked to an {@link AssetType#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.
* <p>
+ * If the message is for a valid linked agent then an {@link AttributeEvent} 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} for execution on an actual device or
+ * service 'things'.
* <p>
* 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.
+ * do this and will vary from protocol to protocol; some 'things' might respond to an actuator command immediately
+ * with a new sensor read, 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>
- * <p>
- * <p>
- * Asset Storage Service processing logic:
+ * <em>Asset Storage Service processing logic</em>
* <p>
* Always tries to persist the attribute value in the DB and allows the message to continue if the commit was
* successful.
* <p>
- * <p>
- * Asset Datapoint Service processing logic:
+ * <em>Asset Datapoint Service processing logic</em>
* <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.
+ * if the commit was successful. TODO Should the datapoint service only store northbound updates?
*/
public class AssetProcessingService extends RouteBuilder implements ContainerService {
@@ -212,6 +204,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
}
// Prevent editing of read only attributes
+ // TODO This also means a rule RHS can't write a read-only attribute with Assets#dispatch!
if (attribute.isReadOnly()) {
LOG.warning("Ignoring " + attributeEvent + ", attribute is read-only in: " + asset);
return;
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 d74504681..948af98e7 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,14 @@
*/
package org.openremote.manager.server.rules;
+import org.drools.core.common.InternalWorkingMemory;
+import org.drools.core.time.InternalSchedulerService;
+import org.drools.core.time.JobContext;
+import org.drools.core.time.JobHandle;
+import org.drools.core.time.impl.DefaultJobHandle;
+import org.drools.core.time.impl.DefaultTimerJobInstance;
+import org.drools.core.time.impl.PointInTimeTrigger;
+import org.drools.core.time.impl.TimerJobInstance;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
@@ -29,6 +37,10 @@ import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
+import org.kie.api.event.rule.ObjectDeletedEvent;
+import org.kie.api.event.rule.ObjectInsertedEvent;
+import org.kie.api.event.rule.ObjectUpdatedEvent;
+import org.kie.api.event.rule.RuleRuntimeEventListener;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieSessionConfiguration;
@@ -43,15 +55,19 @@ import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.notification.NotificationService;
import org.openremote.manager.shared.rules.AssetRuleset;
import org.openremote.manager.shared.rules.GlobalRuleset;
+import org.openremote.manager.shared.rules.Ruleset;
import org.openremote.manager.shared.rules.TenantRuleset;
import org.openremote.model.AttributeEvent;
import org.openremote.model.Consumer;
+import org.openremote.model.asset.AbstractAssetUpdate;
import org.openremote.model.asset.AssetQuery;
import org.openremote.model.asset.AssetUpdate;
import org.openremote.manager.shared.rules.Ruleset;
import org.openremote.model.notification.AlertNotification;
+import org.openremote.model.rules.AssetEvent;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Users;
+import org.openremote.model.rules.Users;
import java.util.*;
import java.util.concurrent.Executors;
@@ -68,7 +84,7 @@ public class RulesDeployment<T extends Ruleset> {
protected final NotificationService notificationService;
final protected AssetStorageService assetStorageService;
final protected AssetProcessingService assetProcessingService;
- final protected Class<T> rulesetType;
+ final protected Class<T> rulesetType;
final protected String id;
// This is here so Clock Type can be set to pseudo from tests
@@ -106,7 +122,7 @@ public class RulesDeployment<T extends Ruleset> {
@SuppressWarnings("unchecked")
public synchronized T[] getAllRulesets() {
- T[]arr = Util.createArray(rulesets.size(), rulesetType);
+ T[] arr = Util.createArray(rulesets.size(), rulesetType);
return rulesets.values().toArray(arr);
}
@@ -161,7 +177,7 @@ public class RulesDeployment<T extends Ruleset> {
*
* @return Whether or not the ruleset deployed successfully
*/
- public synchronized boolean insertRuleset(T ruleset) {
+ public synchronized boolean addRuleset(T ruleset) {
if (ruleset == null || ruleset.getRules() == null || ruleset.getRules().isEmpty()) {
// Assume it's a success if deploying an empty ruleset
LOG.finest("Ruleset is empty so no rules to deploy");
@@ -247,7 +263,7 @@ public class RulesDeployment<T extends Ruleset> {
return addSuccessful;
}
- protected synchronized void retractRuleset(Ruleset ruleset) {
+ protected synchronized void removeRuleset(Ruleset ruleset) {
if (kfs == null) {
return;
}
@@ -302,12 +318,12 @@ public class RulesDeployment<T extends Ruleset> {
KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKModule");
kieBaseModel
- .setDefault(true)
- .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
- .setEventProcessingMode(EventProcessingOption.STREAM)
- .newKieSessionModel("ksession1")
- .setDefault(true)
- .setType(KieSessionModel.KieSessionType.STATEFUL);
+ .setDefault(true)
+ .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
+ .setEventProcessingMode(EventProcessingOption.STREAM)
+ .newKieSessionModel("ksession1")
+ .setDefault(true)
+ .setType(KieSessionModel.KieSessionType.STATEFUL);
kfs = kieServices.newKieFileSystem();
kfs.generateAndWritePomXML(releaseId);
kfs.writeKModuleXML(kieModuleModel.toXML());
@@ -359,6 +375,24 @@ public class RulesDeployment<T extends Ruleset> {
setGlobal("util", UTIL);
knowledgeSession.addEventListener(ruleExecutionLogger);
+
+ knowledgeSession.addEventListener(new RuleRuntimeEventListener() {
+ @Override
+ public void objectInserted(ObjectInsertedEvent event) {
+ LOG.fine("+++ On " + RulesDeployment.this + ", object inserted: " + event.getObject());
+ }
+
+ @Override
+ public void objectUpdated(ObjectUpdatedEvent event) {
+ LOG.fine("^^^ On " + RulesDeployment.this + ", object updated: " + event.getObject());
+ }
+
+ @Override
+ public void objectDeleted(ObjectDeletedEvent event) {
+ LOG.fine("--- On " + RulesDeployment.this + ", object deleted: " + event.getOldObject());
+ }
+ });
+
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to create the rules engine session", e);
error = e;
@@ -368,7 +402,7 @@ public class RulesDeployment<T extends Ruleset> {
// Insert all the facts into the session
List<AssetUpdate> factEntries = new ArrayList<>(facts.keySet());
- factEntries.forEach(factEntry -> insertFactIntoSession(factEntry, true));
+ factEntries.forEach(factEntry -> insertFact(factEntry, true));
LOG.info("Rule engine started");
knowledgeSession.fireAllRules();
@@ -390,7 +424,15 @@ public class RulesDeployment<T extends Ruleset> {
running = false;
}
- protected synchronized void insertFact(AssetUpdate assetUpdate, boolean silent) {
+ protected synchronized FactHandle insertFact(AssetUpdate assetUpdate, boolean silent) {
+ return insertIntoSession(
+ assetUpdate,
+ silent,
+ factHandle -> facts.put(assetUpdate, factHandle)
+ );
+ }
+
+ protected synchronized void updateFact(AssetUpdate assetUpdate, boolean silent) {
// Check if fact already exists using equals()
if (!facts.containsKey(assetUpdate)) {
// Delete any existing fact for this attribute ref
@@ -398,7 +440,7 @@ public class RulesDeployment<T extends Ruleset> {
retractFact(assetUpdate);
if (isRunning()) {
- insertFactIntoSession(assetUpdate, silent);
+ insertFact(assetUpdate, silent);
} else {
facts.put(assetUpdate, null);
}
@@ -409,10 +451,10 @@ 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.attributeRefsEqual(assetUpdate))
- .findFirst()
- .orElse(null);
+ .stream()
+ .filter(au -> au.attributeRefsEqual(assetUpdate))
+ .findFirst()
+ .orElse(null);
FactHandle factHandle = update != null ? facts.get(update) : null;
@@ -422,7 +464,6 @@ public class RulesDeployment<T extends Ruleset> {
if (isRunning()) {
try {
// ... retract it from working memory ...
- LOG.finest("Removed stale fact '" + update + "' in: " + this);
knowledgeSession.delete(factHandle);
int fireCount = knowledgeSession.fireAllRules();
} catch (Exception e) {
@@ -434,45 +475,47 @@ public class RulesDeployment<T extends Ruleset> {
}
}
- protected FactHandle insertFactIntoSession(AssetUpdate assetUpdate, boolean silent) {
- FactHandle factHandle = null;
-
- 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;
+ protected synchronized FactHandle insertEvent(AssetEvent assetEvent, long expirationOffset) {
+ return insertIntoSession(
+ assetEvent,
+ false,
+ factHandle -> scheduleExpiration(assetEvent, factHandle, expirationOffset)
+ );
+ }
- } 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);
+ protected synchronized FactHandle insertIntoSession(AbstractAssetUpdate abstractAssetUpdate,
+ boolean silent,
+ Consumer<FactHandle> afterInsert) {
+ if (!isRunning()) {
+ LOG.fine("Engine is in error state or not running (" + toString() + "), ignoring: " + abstractAssetUpdate);
+ return null;
+ }
+ try {
+ long newFactCount;
+ FactHandle factHandle = knowledgeSession.insert(abstractAssetUpdate);
+ afterInsert.accept(factHandle);
+ LOG.finest("On " + this + ", firing all rules");
+ int fireCount = knowledgeSession.fireAllRules((match) -> !silent || !match.getFactHandles().contains(factHandle));
+ LOG.finest("On " + this + ", fired rules count: " + fireCount);
+
+ 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: "
+ + abstractAssetUpdate);
}
- } else {
- LOG.fine("Engine is in error state or not running (" + toString() + "), ignoring: " + assetUpdate);
+ currentFactCount = newFactCount;
+ return factHandle;
+ } 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);
}
-
- return factHandle;
}
protected Assets createAssetsFacade() {
@@ -559,12 +602,11 @@ public class RulesDeployment<T extends Ruleset> {
};
}
-
protected Users createUsersFacade() {
return new Users() {
@Override
- public RestrictedQuery query() {
+ public Users.RestrictedQuery query() {
RestrictedQuery query = new RestrictedQuery() {
@Override
@@ -601,6 +643,47 @@ public class RulesDeployment<T extends Ruleset> {
};
}
+ /**
+ * Use the internal scheduling of Drools to expire events, so we can coordinate with the internal clock.
+ * Yes, this is a hack.
+ */
+ protected void scheduleExpiration(AssetEvent assetEvent, FactHandle factHandle, long expirationOffset) {
+ InternalSchedulerService sessionScheduler = knowledgeSession.getSessionClock();
+ JobHandle jobHandle = new DefaultJobHandle(assetEvent.getId().hashCode());
+ class AssetEventExpireJobContext implements JobContext {
+ public JobHandle handle;
+
+ @Override
+ public void setJobHandle(JobHandle jobHandle) {
+ this.handle = jobHandle;
+ }
+
+ @Override
+ public JobHandle getJobHandle() {
+ return handle;
+ }
+
+ @Override
+ public InternalWorkingMemory getWorkingMemory() {
+ return null;
+ }
+ }
+ TimerJobInstance timerJobInstance = new DefaultTimerJobInstance(
+ ctx -> {
+ LOG.fine("On " + RulesDeployment.this + ", fact expired, deleting: " + assetEvent);
+ synchronized (RulesDeployment.this) {
+ knowledgeSession.delete(factHandle);
+ }
+ },
+ new AssetEventExpireJobContext(),
+ new PointInTimeTrigger(knowledgeSession.getSessionClock().getCurrentTime() + expirationOffset, null, null),
+ jobHandle,
+ sessionScheduler
+ );
+ sessionScheduler.internalSchedule(timerJobInstance);
+
+ }
+
protected synchronized String getRulesetDebug() {
return Arrays.toString(rulesets.values().stream().map(rd ->
rd.getClass().getSimpleName()
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 948d2b2a0..5505d04e4 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
@@ -21,13 +21,13 @@ package org.openremote.manager.server.rules;
import elemental.json.JsonObject;
import org.apache.camel.builder.RouteBuilder;
+import org.drools.core.base.evaluators.TimeIntervalParser;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.util.Pair;
-import org.openremote.container.util.Util;
import org.openremote.manager.server.asset.AssetProcessingService;
import org.openremote.manager.server.asset.AssetStorageService;
import org.openremote.manager.server.asset.ServerAsset;
@@ -39,8 +39,8 @@ 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.rules.AssetEvent;
import org.openremote.model.util.JsonUtil;
import java.util.*;
@@ -50,6 +50,7 @@ import java.util.logging.Logger;
import java.util.stream.Collectors;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
+import static org.openremote.container.util.MapAccess.getString;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
/**
@@ -64,7 +65,12 @@ import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceE
* with the same scope is not guaranteed)
*/
public class RulesService extends RouteBuilder implements ContainerService, Consumer<AssetUpdate> {
+
private static final Logger LOG = Logger.getLogger(RulesService.class.getName());
+
+ public static final String RULES_EVENT_EXPIRES = "RULES_EVENT_EXPIRES";
+ public static final String RULES_EVENT_EXPIRES_DEFAULT = "1h";
+
protected PersistenceService persistenceService;
protected RulesetStorageService rulesetStorageService;
protected ManagerIdentityService identityService;
@@ -75,11 +81,14 @@ 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<>();
+ protected String configEventExpires;
+
@Override
public void init(Container container) throws Exception {
persistenceService = container.getService(PersistenceService.class);
@@ -89,11 +98,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
assetStorageService = container.getService(AssetStorageService.class);
assetProcessingService = container.getService(AssetProcessingService.class);
container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
+
+ configEventExpires = getString(container.getConfig(), RULES_EVENT_EXPIRES, RULES_EVENT_EXPIRES_DEFAULT);
}
@Override
public void configure() throws Exception {
- // If any ruleset was modified in the database then check its' status and retract, insert or update it
+ // If any ruleset was modified in the database then check its' status and undeploy, deploy, or update it
from(PERSISTENCE_TOPIC)
.filter(isPersistenceEventForEntityType(Ruleset.class))
.process(exchange -> {
@@ -101,7 +112,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
processRulesetChange((Ruleset) persistenceEvent.getEntity(), persistenceEvent.getCause());
});
- // If any tenant was modified in the database then check its' status and retract, insert or update any
+ // If any tenant was modified in the database then check its' status and undeploy, deploy or update any
// associated rulesets
from(PERSISTENCE_TOPIC)
.filter(isPersistenceEventForEntityType(Tenant.class))
@@ -124,7 +135,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
@Override
public void start(Container container) throws Exception {
LOG.info("Deploying global rulesets");
- rulesetStorageService.findEnabledGlobalRulesets().forEach(this::insertGlobalRuleset);
+ rulesetStorageService.findEnabledGlobalRulesets().forEach(this::deployGlobalRuleset);
LOG.info("Deploying tenant rulesets");
activeTenantIds = identityService.getActiveTenantIds();
@@ -133,29 +144,29 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
.filter(rd ->
Arrays.stream(activeTenantIds)
.anyMatch(tenantId -> rd.getRealmId().equals(tenantId))
- ).forEach(this::insertTenantRuleset);
+ ).forEach(this::deployTenantRuleset);
LOG.info("Deploying asset rulesets");
// Group by asset ID then tenant and check tenant is enabled
- insertAssetRulesets(rulesetStorageService.findEnabledAssetRulesets());
+ deployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets());
LOG.info("Loading all assets with fact attributes to initialize state of rules engines");
- List<Pair<ServerAsset, List<AssetAttribute>>> assetRuleAttributesList = findRuleAttributes(null, null);
+ List<Pair<ServerAsset, List<AssetAttribute>>> assetRuleAttributesList = findRuleFactAttributes(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);
- });
+ .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);
+ updateFact(update, true);
});
+ });
}
@Override
@@ -179,9 +190,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
@Override
public void accept(AssetUpdate assetUpdate) {
if (assetUpdate.getAttribute().isRulesFact()) {
- insertFact(assetUpdate, false);
+ updateFact(assetUpdate, false);
+ } else if (assetUpdate.getAttribute().isRulesEvent()) {
+ process(new AssetEvent(assetUpdate));
} else {
- LOG.finest("Ignoring update as attribute is not a rules fact: " + assetUpdate);
+ LOG.finest("Ignoring update as attribute is not a rules fact or rules event: " + assetUpdate);
}
}
@@ -202,7 +215,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
if (tenantDeployment != null) {
// Use a copy of the list to avoid concurrent modification problems in retract
new ArrayList<>(Arrays.asList(tenantDeployment.getAllRulesets()))
- .forEach(this::retractTenantRuleset);
+ .forEach(this::undeployTenantRuleset);
}
// Remove any asset deployments for assets in this realm
@@ -210,16 +223,16 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
new ArrayList<>(assetDeployments.values()).stream().flatMap(
assetRulesDeployment -> Arrays.stream(assetRulesDeployment.getAllRulesets())
).filter(ruleset -> ruleset.getRealmId().equals(tenant.getId()))
- .forEach(this::retractAssetRuleset);
+ .forEach(this::undeployAssetRuleset);
} else {
- // Insert tenant deployment for this tenant if it has any rulesets
+ // Create tenant deployment for this tenant if it has any rulesets
rulesetStorageService
.findEnabledTenantRulesets(tenant.getId())
- .forEach(this::insertTenantRuleset);
+ .forEach(this::deployTenantRuleset);
- // Insert any asset deployments for assets in this realm that have rulesets
- insertAssetRulesets(rulesetStorageService.findEnabledAssetRulesets(tenant.getId()));
+ // Create any asset deployments for assets in this realm that have rulesets
+ deployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets(tenant.getId()));
}
}
@@ -230,9 +243,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
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()));
+ new AssetAttribute(loadedAsset.getId(),
+ attribute.getName(),
+ attribute.getJsonObject()));
};
switch (persistenceEvent.getCause()) {
@@ -242,14 +255,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
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);
- });
+ .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);
+ updateFact(update, true);
+ });
break;
case UPDATE:
@@ -262,66 +275,66 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
AssetAttributes newAttributes = new AssetAttributes((JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);
List<AssetAttribute> oldFactAttributes = oldAttributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .collect(Collectors.toList());
+ .filter(AssetAttribute::isRulesFact)
+ .collect(Collectors.toList());
List<AssetAttribute> newFactAttributes = newAttributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .collect(Collectors.toList());
+ .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()
- .filter(oldFactAttribute -> newFactAttributes
- .stream()
- .noneMatch(newFactAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison
- oldFactAttribute.getJsonObject(),
- newFactAttribute.getJsonObject(),
- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
- )
+ .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);
- });
+ )
+ .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()
- .filter(newFactAttribute -> oldFactAttributes
- .stream()
- .noneMatch(oldFactAttribute ->
- JsonUtil.equals( // Ignore the timestamp in comparison
- oldFactAttribute.getJsonObject(),
- newFactAttribute.getJsonObject(),
- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)
- )
- )
+ .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);
- });
+ )
+ .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);
+ updateFact(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);
- });
+ .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;
}
}
@@ -329,29 +342,29 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected synchronized void processRulesetChange(Ruleset ruleset, PersistenceEvent.Cause cause) {
if (cause == PersistenceEvent.Cause.DELETE || !ruleset.isEnabled()) {
if (ruleset instanceof GlobalRuleset) {
- retractGlobalRuleset((GlobalRuleset) ruleset);
+ undeployGlobalRuleset((GlobalRuleset) ruleset);
} else if (ruleset instanceof TenantRuleset) {
- retractTenantRuleset((TenantRuleset) ruleset);
+ undeployTenantRuleset((TenantRuleset) ruleset);
} else if (ruleset instanceof AssetRuleset) {
- retractAssetRuleset((AssetRuleset) ruleset);
+ undeployAssetRuleset((AssetRuleset) ruleset);
}
} else {
if (ruleset instanceof GlobalRuleset) {
- RulesDeployment newEngine = insertGlobalRuleset((GlobalRuleset)ruleset);
+ RulesDeployment newEngine = deployGlobalRuleset((GlobalRuleset) ruleset);
if (newEngine != null) {
// Push all existing facts into the engine
- facts.forEach(assetUpdate -> newEngine.insertFact(assetUpdate, true));
+ facts.forEach(assetUpdate -> newEngine.updateFact(assetUpdate, true));
}
} else if (ruleset instanceof TenantRuleset) {
- RulesDeployment newEngine = insertTenantRuleset((TenantRuleset) ruleset);
+ RulesDeployment newEngine = deployTenantRuleset((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);
+ newEngine.updateFact(assetUpdate, true);
}
});
}
@@ -360,11 +373,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Must reload from the database, the ruleset might not be completely hydrated on INSERT or UPDATE
AssetRuleset assetRuleset = rulesetStorageService.findEnabledAssetRuleset(ruleset.getId());
- RulesDeployment newEngine = insertAssetRuleset(assetRuleset);
+ RulesDeployment newEngine = deployAssetRuleset(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));
+ .forEach(assetUpdate -> newEngine.updateFact(assetUpdate, true));
}
}
@@ -372,10 +385,10 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
/**
- * Inserts the ruleset into the global engine creating the engine if necessary; if the engine was created then it
+ * Deploy 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) {
+ protected synchronized RulesDeployment<GlobalRuleset> deployGlobalRuleset(GlobalRuleset ruleset) {
boolean created = globalDeployment == null;
// Global rules have access to everything in the system
@@ -383,23 +396,23 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
globalDeployment = new RulesDeployment<>(assetStorageService, notificationService, assetProcessingService, GlobalRuleset.class, "GLOBAL");
}
- globalDeployment.insertRuleset(ruleset);
+ globalDeployment.addRuleset(ruleset);
return created ? globalDeployment : null;
}
- protected synchronized void retractGlobalRuleset(GlobalRuleset ruleset) {
+ protected synchronized void undeployGlobalRuleset(GlobalRuleset ruleset) {
if (globalDeployment == null) {
return;
}
- globalDeployment.retractRuleset(ruleset);
+ globalDeployment.removeRuleset(ruleset);
if (globalDeployment.isEmpty()) {
globalDeployment = null;
}
}
- protected synchronized RulesDeployment<TenantRuleset> insertTenantRuleset(TenantRuleset ruleset) {
+ protected synchronized RulesDeployment<TenantRuleset> deployTenantRuleset(TenantRuleset ruleset) {
final boolean[] created = {false};
// Look for existing deployment for this tenant
@@ -409,25 +422,25 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
return new RulesDeployment<>(assetStorageService,notificationService, assetProcessingService, TenantRuleset.class, realmId);
});
- deployment.insertRuleset(ruleset);
+ deployment.addRuleset(ruleset);
return created[0] ? deployment : null;
}
- protected synchronized void retractTenantRuleset(TenantRuleset ruleset) {
+ protected synchronized void undeployTenantRuleset(TenantRuleset ruleset) {
RulesDeployment<TenantRuleset> deployment = tenantDeployments.get(ruleset.getRealmId());
if (deployment == null) {
return;
}
- deployment.retractRuleset(ruleset);
+ deployment.removeRuleset(ruleset);
if (deployment.isEmpty()) {
tenantDeployments.remove(ruleset.getRealmId());
}
}
- protected void insertAssetRulesets(List<AssetRuleset> rulesets) {
+ protected void deployAssetRulesets(List<AssetRuleset> rulesets) {
rulesets
.stream()
.collect(Collectors.groupingBy(AssetRuleset::getAssetId))
@@ -451,11 +464,11 @@ 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::insertAssetRuleset);
+ .forEach(this::deployAssetRuleset);
});
}
- protected synchronized RulesDeployment<AssetRuleset> insertAssetRuleset(AssetRuleset ruleset) {
+ protected synchronized RulesDeployment<AssetRuleset> deployAssetRuleset(AssetRuleset ruleset) {
final boolean[] created = {false};
// Look for existing deployment for this asset
@@ -465,24 +478,53 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
return new RulesDeployment<>(assetStorageService,notificationService, assetProcessingService, AssetRuleset.class, assetId);
});
- deployment.insertRuleset(ruleset);
+ deployment.addRuleset(ruleset);
return created[0] ? deployment : null;
}
- protected synchronized void retractAssetRuleset(AssetRuleset ruleset) {
+ protected synchronized void undeployAssetRuleset(AssetRuleset ruleset) {
RulesDeployment<AssetRuleset> deployment = assetDeployments.get(ruleset.getAssetId());
if (deployment == null) {
return;
}
- deployment.retractRuleset(ruleset);
+ deployment.removeRuleset(ruleset);
if (deployment.isEmpty()) {
assetDeployments.remove(ruleset.getAssetId());
}
}
- protected synchronized void insertFact(AssetUpdate assetUpdate, boolean skipStatusCheck) {
+
+ protected synchronized void process(AssetEvent assetEvent) {
+ // TODO: implement rules processing error state handling
+
+ // Get the chain of rule engines that we need to pass through
+ List<RulesDeployment> rulesDeployments = getEnginesInScope(assetEvent.getRealmId(), assetEvent.getPathFromRoot());
+
+ if (rulesDeployments.size() == 0) {
+ LOG.fine("Ignoring asset event as there are no matching rules deployments: " + assetEvent);
+ }
+
+ // Check that all engines in the scope are not in ERROR state
+ if (rulesDeployments.stream().anyMatch(RulesDeployment::isError)) {
+ LOG.severe("At least one rule engine is in an error state so cannot process event:" + assetEvent);
+ return;
+ }
+
+ // Pass through each engine and try and insert the fact
+ for (RulesDeployment deployment : rulesDeployments) {
+
+ // Any exceptions in rule RHS will bubble up and the engine would be marked as in ERROR so future
+ // updates will be blocked
+ String eventExpires = assetEvent.getExpires() != null ? assetEvent.getExpires() : configEventExpires;
+ long expirationOffset = TimeIntervalParser.parseSingle(eventExpires);
+
+ deployment.insertEvent(assetEvent, expirationOffset);
+ }
+ }
+
+ protected synchronized void updateFact(AssetUpdate assetUpdate, boolean skipStatusCheck) {
// TODO: implement rules processing error state handling
// Get the chain of rule engines that we need to pass through
@@ -514,7 +556,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// 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);
+ deployment.updateFact(assetUpdate, skipStatusCheck);
if (!skipStatusCheck) {
// We have to check status between each engine insert as a rule in the engine could have updated
@@ -529,7 +571,6 @@ 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.getPathFromRoot());
@@ -550,9 +591,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected List<AssetUpdate> getFactsInScope(String assetId) {
return facts
- .stream()
- .filter(assetUpdate -> Arrays.asList(assetUpdate.getPathFromRoot()).contains(assetId))
- .collect(Collectors.toList());
+ .stream()
+ .filter(assetUpdate -> Arrays.asList(assetUpdate.getPathFromRoot()).contains(assetId))
+ .collect(Collectors.toList());
}
protected List<RulesDeployment> getEnginesInScope(String assetRealmId, String[] assetPath) {
@@ -582,22 +623,22 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
return rulesDeployments;
}
- protected List<Pair<ServerAsset, List<AssetAttribute>>> findRuleAttributes(AssetQuery.TenantPredicate tenantPredicate, AssetQuery.ParentPredicate parentPredicate) {
+ protected List<Pair<ServerAsset, List<AssetAttribute>>> findRuleFactAttributes(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))
- ));
+ 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());
+ .filter(AssetAttribute::isRulesFact).collect(Collectors.toList());
return new Pair<>(asset, ruleAttributes);
}).collect(Collectors.toList());
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
index 2278eb67d..e94b14141 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
@@ -302,20 +302,20 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment1Livingroom.setType(ROOM);
AssetAttributes apartment1LivingroomAttributes = new AssetAttributes();
apartment1LivingroomAttributes.put(
- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))
+ new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false))
.setMeta(
new Meta().add(
- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))
+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Sensor"))
).add(
- new MetaItem(AssetMeta.RULES_FACT, Json.create(true))
+ new MetaItem(AssetMeta.RULES_EVENT, Json.create(true))
)
),
- new AssetAttribute("presenceCount15m", AttributeType.INTEGER, Json.create(0))
+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))
.setMeta(
new Meta().add(
- new MetaItem(AssetMeta.LABEL, Json.create("Presence Count 15m"))
+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))
).add(
- new MetaItem(AssetMeta.READ_ONLY, Json.create(true))
+ new MetaItem(AssetMeta.RULES_FACT, Json.create(true))
)
),
new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Json.create(true))
@@ -424,20 +424,20 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment2Livingroom.setType(ROOM);
AssetAttributes apartment2LivingroomAttributes = new AssetAttributes();
apartment2LivingroomAttributes.put(
- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))
+ new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false))
.setMeta(
new Meta().add(
- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))
+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Sensor"))
).add(
- new MetaItem(AssetMeta.RULES_FACT, Json.create(true))
+ new MetaItem(AssetMeta.RULES_EVENT, Json.create(true))
)
),
- new AssetAttribute("presenceCount15m", AttributeType.INTEGER, Json.create(0))
+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))
.setMeta(
new Meta().add(
- new MetaItem(AssetMeta.LABEL, Json.create("Presence Count 15m"))
+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))
).add(
- new MetaItem(AssetMeta.READ_ONLY, Json.create(true))
+ new MetaItem(AssetMeta.RULES_FACT, Json.create(true))
)
),
new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Json.create(true))
@@ -486,20 +486,20 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment3Livingroom.setType(ROOM);
AssetAttributes apartment3LivingroomAttributes = new AssetAttributes();
apartment3LivingroomAttributes.put(
- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))
+ new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false))
.setMeta(
new Meta().add(
- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))
+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Sensor"))
).add(
- new MetaItem(AssetMeta.RULES_FACT, Json.create(true))
+ new MetaItem(AssetMeta.RULES_EVENT, Json.create(true))
)
),
- new AssetAttribute("presenceCount15m", AttributeType.INTEGER, Json.create(0))
+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))
.setMeta(
new Meta().add(
- new MetaItem(AssetMeta.LABEL, Json.create("Presence Count 15m"))
+ new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected"))
).add(
- new MetaItem(AssetMeta.READ_ONLY, Json.create(true))
+ new MetaItem(AssetMeta.RULES_FACT, Json.create(true))
)
),
new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Json.create(true))
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
index fb775c170..42b56c7a1 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/RulesDemoSetup.java
@@ -49,9 +49,14 @@ public class RulesDemoSetup extends AbstractManagerSetup {
// ################################ Rules demo data ###################################
- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentActions.drl")) {
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentAllLightsOff.drl")) {
String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
- Ruleset ruleset = new TenantRuleset("Demo Apartment Actions", keycloakDemoSetup.customerATenant.getId(), rules);
+ Ruleset ruleset = new TenantRuleset("Demo Apartment - All Lights Off", keycloakDemoSetup.customerATenant.getId(), rules);
+ apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
+ }
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetection.drl")) {
+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
+ Ruleset ruleset = new TenantRuleset("Demo Apartment - Presence Detection", keycloakDemoSetup.customerATenant.getId(), rules);
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
}
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentActions.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl
similarity index 91%
rename from manager/server/src/main/resources/demo/rules/DemoApartmentActions.drl
rename to manager/server/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl
index 9da4f3f2d..4eb9e6f4e 100644
--- a/manager/server/src/main/resources/demo/rules/DemoApartmentActions.drl
+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl
@@ -7,7 +7,7 @@ import elemental.json.Json;
global java.util.logging.Logger LOG;
global org.openremote.model.rules.Assets assets;
-rule "--Switch room lights off when apartment ALL LIGHTS OFF switch is off"
+rule "Switch room lights off when apartment ALL LIGHTS OFF switch is off"
when
// In an asset of type RESIDENCE the power switch is turned off
$e: AssetUpdate(attributeName == "allLightsOffSwitch", type == AssetType.RESIDENCE, value.asBoolean() == false)
diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl
new file mode 100644
index 000000000..c9be0061e
--- /dev/null
+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl
@@ -0,0 +1,29 @@
+package org.openremote.test.rules;
+
+import org.openremote.model.*;
+import org.openremote.model.asset.*
+import org.openremote.model.rules.*
+import elemental.json.Json;
+
+global java.util.logging.Logger LOG;
+global org.openremote.model.rules.Assets assets;
+
+rule "Set presence detected if sensor is triggered multiple times"
+when
+ // The presence sensor of a room is triggered
+ $pir : AssetEvent(type == AssetType.ROOM, attributeName == "presenceSensor", value.asBoolean)
+ // More than 2 times in the last 15 minutes
+ Number(intValue > 2) from accumulate(
+ $pir2 : AssetEvent(id == $pir.id, attributeName == "presenceSensor", type == AssetType.ROOM, value.asBoolean) over window:time(15m),
+ count($pir2)
+ )
+ // And the presence latch is not set already
+ AssetUpdate(id == $pir.getId(), attributeName == "presenceDetected", !value.asBoolean)
+
+then
+ LOG.info("### PRESENCE DETECTED IN ROOM: " + $pir);
+ // Set the presence latch of the room
+ assets.dispatch(
+ new AttributeEvent($pir.getId(), "presenceDetected", Json.create(true))
+ );
+end
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 5aa435679..5f1698f4e 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
@@ -108,7 +108,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
def customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.isRunning()
- assert customerAEngine.rulesets.size() == 1
+ assert customerAEngine.rulesets.size() == 2
assert updatesPassedStartOfProcessingChain.size() == 0
assert updatesReachedEndOfProcessingChain.size() == 0
}
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 9cc2abc8f..0d1cac9d1 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
@@ -1,6 +1,8 @@
package org.openremote.test.rules
import elemental.json.Json
+import org.drools.core.time.impl.PseudoClockScheduler
+import org.kie.api.runtime.conf.ClockTypeOption
import org.openremote.manager.server.asset.AssetProcessingService
import org.openremote.manager.server.asset.AssetStorageService
import org.openremote.manager.server.rules.RulesDeployment
@@ -15,11 +17,13 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import static java.util.concurrent.TimeUnit.*
+
class ApartmentActionsTest extends Specification implements ManagerContainerTrait {
- def "Check rules RHS action execution"() {
+ def "All Lights Off"() {
given: "expected conditions"
- def conditions = new PollingConditions(timeout: 5)
+ def conditions = new PollingConditions(timeout: 5, delay: 1)
and: "the container is started"
def serverPort = findEphemeralPort()
@@ -64,4 +68,88 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
cleanup: "the server should be stopped"
stopContainer(container)
}
+
+ def "Presence Detection"() {
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 5, delay: 1)
+
+ and: "a pseudo rules engine clock"
+ RulesDeployment.DefaultClockType = ClockTypeOption.get("pseudo")
+ PseudoClockScheduler sessionClock
+
+ and: "the container is started"
+ def serverPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def rulesDemoSetup = container.getService(SetupService.class).getTaskOfType(RulesDemoSetup.class)
+ def rulesService = container.getService(RulesService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ RulesDeployment customerAEngine = null
+
+ expect: "the rule engines to become available and be running"
+ conditions.eventually {
+ customerAEngine = rulesService.tenantDeployments.get(keycloakDemoSetup.customerATenant.id)
+ assert customerAEngine != null
+ assert customerAEngine.isRunning()
+ assert customerAEngine.knowledgeSession.factCount == 8
+ }
+
+ and: "the presence latch of the room should not be set"
+ def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !new AssetAttributes(livingRoomAsset.getAttributes()).get("presenceDetected").valueAsBoolean
+
+ and: "the presence latch of the other room should not be set"
+ def otherLivingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+ assert !new AssetAttributes(otherLivingRoomAsset.getAttributes()).get("presenceDetected").valueAsBoolean
+
+ when: "we have prepared a rules clock"
+ sessionClock = customerAEngine.sessionClock as PseudoClockScheduler
+ // Set the session clock to wall time, as event expiration offsets are based on wall time
+ sessionClock.advanceTime(System.currentTimeMillis(), MILLISECONDS)
+
+ and: "several presence sensor events are triggered in the room"
+ for (i in 0..2) {
+ def livingroomPresenceChange = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "presenceSensor", Json.create(true)
+ )
+ assetProcessingService.updateAttributeValue(livingroomPresenceChange)
+ sessionClock.advanceTime(2, MINUTES)
+ }
+
+ and: "several presence sensor events are triggered in the other room (but not enough to trigger 'detection')"
+ for (i in 0..2) {
+ def livingroomPresenceChange = new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId, "presenceSensor", Json.create(true)
+ )
+ assetProcessingService.updateAttributeValue(livingroomPresenceChange)
+ sessionClock.advanceTime(10, MINUTES)
+ }
+
+ then: "the presence latch of the room should be set"
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert new AssetAttributes(asset.getAttributes()).get("presenceDetected").valueAsBoolean
+ }
+
+ and: "the presence latch of the other room should NOT be set"
+ conditions.eventually {
+ def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+ assert !new AssetAttributes(asset.getAttributes()).get("presenceDetected").valueAsBoolean
+ }
+
+ when: "time is advanced enough to trigger event expiration"
+ sessionClock.advanceTime(1, HOURS)
+ customerAEngine.knowledgeSession.fireAllRules()
+
+ then: "the events should have been expired and retracted automatically from the knowledge session"
+ conditions.eventually {
+ assert customerAEngine.knowledgeSession.factCount == 8
+ }
+
+ cleanup: "the server should be stopped"
+ RulesDeployment.DefaultClockType = null
+ stopContainer(container)
+ }
}
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
index 872c985c2..f7fb181f3 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
@@ -1,5 +1,7 @@
package org.openremote.test.rules
+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.rules.RulesetStorageService
@@ -43,6 +45,8 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
def rulesService = container.getService(RulesService.class)
def rulesetStorageService = container.getService(RulesetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
and: "some test rulesets have been imported"
Ruleset ruleset = new GlobalRuleset(
diff --git a/model/build.gradle b/model/build.gradle
index 4dfb09d35..667e649dd 100644
--- a/model/build.gradle
+++ b/model/build.gradle
@@ -7,6 +7,7 @@ dependencies {
compile "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:$javaxPersistenceVersion"
compile "org.hibernate:hibernate-core:$hibernateVersion"
compile "org.jboss.logging:jboss-logging-annotations:$jbossLoggingAnnotationsVersion"
+ compile "org.kie:kie-api:$droolsVersion"
}
jar {
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
index 5e258ca80..7e6a5c0d9 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
@@ -131,4 +131,12 @@ public abstract class AbstractAssetAttribute<CHILD extends AbstractAssetAttribut
return hasMetaItem(RULES_FACT) && firstMetaItem(RULES_FACT).isValueTrue();
}
+ public boolean isRulesEvent() {
+ return hasMetaItem(RULES_EVENT) && firstMetaItem(RULES_EVENT).isValueTrue();
+ }
+
+ public String getRulesEventExpires() {
+ return hasMetaItem(RULES_EVENT_EXPIRES) ? firstMetaItem(RULES_EVENT_EXPIRES).getValueAsString() : null;
+ }
+
}
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
new file mode 100644
index 000000000..0b6892f59
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.asset;
+
+import elemental.json.JsonValue;
+import org.openremote.model.AttributeType;
+import org.openremote.model.util.JsonUtil;
+
+import java.util.Date;
+
+/**
+ * An asset attribute value change that can be handled by a sequence of processors.
+ * This class layout is convenient for writing expressions that match getters, while
+ * carrying as much asset details as needed.
+ */
+public abstract class AbstractAssetUpdate {
+
+ final protected AbstractAssetAttribute attribute;
+
+ final protected Date createdOn;
+
+ final protected String id;
+
+ final protected String name;
+
+ final protected String typeString;
+
+ final protected AssetType type;
+
+ final protected String[] pathFromRoot;
+
+ final protected String parentId;
+
+ final protected String parentName;
+
+ final protected String parentTypeString;
+
+ final protected AssetType parentType;
+
+ final protected String realmId;
+
+ final protected String tenantRealm;
+
+ final protected double[] coordinates;
+
+ final protected JsonValue oldValue;
+
+ final protected long oldValueTimestamp;
+
+ // True if the update was initiated by a protocol and is being processed northbound
+ protected boolean northbound;
+
+ public AbstractAssetUpdate(Asset asset, AbstractAssetAttribute attribute) {
+ this(asset, attribute, null, 0, false);
+ }
+
+ public AbstractAssetUpdate(Asset asset, AbstractAssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {
+ this(
+ attribute,
+ asset.getCreatedOn(),
+ asset.getId(),
+ asset.getName(),
+ asset.getType(),
+ asset.getWellKnownType(),
+ asset.getReversePath(),
+ asset.getParentId(),
+ asset.getParentName(),
+ asset.getParentType(),
+ asset.getParentType() != null ? AssetType.getByValue(asset.getParentType()) : null,
+ asset.getRealmId(),
+ asset.getTenantRealm(),
+ asset.getCoordinates(),
+ oldValue,
+ oldValueTimestamp,
+ northbound
+ );
+ }
+
+ public AbstractAssetUpdate(AbstractAssetUpdate that) {
+ this(
+ that.attribute,
+ that.createdOn,
+ that.id,
+ that.name,
+ that.typeString,
+ that.type,
+ that.pathFromRoot,
+ that.parentId,
+ that.parentName,
+ that.parentTypeString,
+ that.parentType,
+ that.realmId,
+ that.tenantRealm,
+ that.coordinates,
+ that.oldValue,
+ that.oldValueTimestamp,
+ that.northbound
+ );
+ }
+
+ protected AbstractAssetUpdate(AbstractAssetAttribute attribute,
+ Date createdOn, String id, String name, String typeString, AssetType type,
+ String[] pathFromRoot, String parentId, String parentName, String parentTypeString, AssetType parentType,
+ String realmId, String tenantRealm,
+ double[] coordinates,
+ JsonValue oldValue,
+ long oldValueTimestamp,
+ boolean northbound) {
+ this.attribute = attribute;
+ this.createdOn = createdOn;
+ this.id = id;
+ this.name = name;
+ this.typeString = typeString;
+ this.type = type;
+ if (pathFromRoot == null) {
+ throw new IllegalArgumentException("Empty path (asset not completely loaded?): " + id);
+ }
+ this.pathFromRoot = pathFromRoot;
+ this.parentId = parentId;
+ this.parentName = parentName;
+ this.parentTypeString = parentTypeString;
+ this.parentType = parentType;
+ this.realmId = realmId;
+ this.tenantRealm = tenantRealm;
+ this.coordinates = coordinates;
+ this.oldValue = oldValue;
+ this.oldValueTimestamp = oldValueTimestamp;
+ this.northbound = northbound;
+ }
+
+ public Date getCreatedOn() {
+ return createdOn;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getTypeString() {
+ return typeString;
+ }
+
+ public AssetType getType() {
+ return type;
+ }
+
+ public String[] getPathFromRoot() {
+ return pathFromRoot;
+ }
+
+ public String getParentId() {
+ return parentId;
+ }
+
+ public String getParentName() {
+ return parentName;
+ }
+
+ public String getParentTypeString() {
+ return parentTypeString;
+ }
+
+ public AssetType getParentType() {
+ return parentType;
+ }
+
+ public String getRealmId() {
+ return realmId;
+ }
+
+ public String getTenantRealm() {
+ return tenantRealm;
+ }
+
+ public double[] getCoordinates() {
+ return coordinates;
+ }
+
+ public JsonValue getOldValue() {
+ return oldValue;
+ }
+
+ public long getOldValueTimestamp() {
+ return oldValueTimestamp;
+ }
+
+ public boolean isNorthbound() {
+ return northbound;
+ }
+
+ public JsonValue getValue() {
+ return attribute.getValue();
+ }
+
+ public String getAttributeName() {
+ return attribute.getName();
+ }
+
+ public long getValueTimestamp() {
+ return attribute.getValueTimestamp();
+ }
+
+ public AttributeType getAttributeType() {
+ return attribute.getType();
+ }
+
+ public boolean isValueChanged() {
+ return !JsonUtil.equals(attribute.getValue(), oldValue);
+ }
+
+ /**
+ * This is here because {@link #attribute} is not always publicly accessible
+ */
+ public boolean attributeRefsEqual(AbstractAssetUpdate assetUpdate) {
+ return !(assetUpdate == null || assetUpdate.attribute == null)
+ && assetUpdate.attribute.getAttributeRef().equals(attribute.getAttributeRef());
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ AbstractAssetUpdate that = (AbstractAssetUpdate) o;
+
+ return id.equals(that.id) &&
+ getAttributeName().equalsIgnoreCase(that.getAttributeName()) &&
+ JsonUtil.equals(getValue(), that.getValue()) &&
+ getValueTimestamp() == that.getValueTimestamp() &&
+ ((oldValue == null && that.oldValue == null) || (oldValue != null && JsonUtil.equals(oldValue, that.oldValue))) &&
+ oldValueTimestamp == that.oldValueTimestamp;
+ }
+
+ @Override
+ public int hashCode() {
+ return id.hashCode() + getAttributeName().hashCode() + JsonUtil.hashCode(getValue())
+ + Long.hashCode(getValueTimestamp())
+ + (oldValue != null ? JsonUtil.hashCode(oldValue) : 0) + Long.hashCode(oldValueTimestamp);
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "id='" + getId() + '\'' +
+ ", name='" + getName() + '\'' +
+ ", typeString='" + getType() + '\'' +
+ ", attributeName='" + getAttributeName() + '\'' +
+ ", attributeType=" + getAttributeType() +
+ ", value='" + getValue().toJson() + '\'' +
+ ", valueTimestamp=" + getValueTimestamp() +
+ ", oldValue='" + (getOldValue() != null ? getOldValue().toJson() : "null") + '\'' +
+ ", oldValueTimestamp=" + getOldValueTimestamp() +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index e42d3d544..45727bdbd 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -110,9 +110,26 @@ public enum AssetMeta {
STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), JsonType.BOOLEAN),
/**
- * Should attribute writes be processed by the rules engines and inserted as facts into their knowledge sessions.
+ * Should attribute writes be processed by the rules engines as facts in knowledge sessions, with a lifecycle
+ * that reflects the state of the asset attribute (the {@link AssetUpdate} facts in the rules sessions are kept
+ * in sync with asset changes).
*/
- RULES_FACT(ASSET_META_NAMESPACE + ":rulesFact", new Access(true, false, true), JsonType.BOOLEAN);
+ RULES_FACT(ASSET_META_NAMESPACE + ":rulesFact", new Access(true, false, true), JsonType.BOOLEAN),
+
+ /**
+ * Should attribute writes be processed by the rules engines as events in knowledge sessions with limited
+ * lifecycle that reflects how the event is processed (the {@link org.openremote.model.rules.AssetEvent} facts
+ * in the rules sessions are expired automatically after a certain time and/or if they can no longer be matched
+ * by time operations).
+ */
+ RULES_EVENT(ASSET_META_NAMESPACE + ":rulesEvent", new Access(true, false, true), JsonType.BOOLEAN),
+
+ /**
+ * Override rules event expiration, for example "1h30m". Remove {@link org.openremote.model.rules.AssetEvent}
+ * facts from the rules sessions if they are older than this value (using event source timestamp, not event
+ * processing time).
+ */
+ RULES_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":rulesEventExpires", new Access(true, false, true), JsonType.NUMBER);
final protected String name;
final protected Access access;
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 695f65819..149cd8095 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
@@ -20,15 +20,12 @@
package org.openremote.model.asset;
import elemental.json.JsonValue;
-import org.openremote.model.AttributeType;
-import org.openremote.model.util.JsonUtil;
-
-import java.util.Date;
/**
- * An asset attribute value change that can be handled by a sequence of processors.
+ * An asset attribute value change that can be handled by a sequence of processors
+ * with status and error handling.
*/
-public class AssetUpdate {
+public class AssetUpdate extends AbstractAssetUpdate {
/**
* Processors of updates can change the status to direct further processing.
@@ -61,130 +58,16 @@ public class AssetUpdate {
COMPLETED
}
- final protected AbstractAssetAttribute attribute;
-
- final protected Date createdOn;
-
- final protected String id;
-
- final protected String name;
-
- final protected String typeString;
-
- final protected AssetType type;
-
- final protected String[] pathFromRoot;
-
- final protected String parentId;
-
- final protected String parentName;
-
- final protected String parentTypeString;
-
- final protected AssetType parentType;
-
- final protected String realmId;
-
- final protected String tenantRealm;
-
- final protected double[] coordinates;
-
- final protected JsonValue oldValue;
-
- final protected long oldValueTimestamp;
-
protected Status status = Status.CONTINUE;
protected Throwable error;
- // True if the update was initiated by a protocol and is being processed northbound
- protected boolean northbound;
-
public AssetUpdate(Asset asset, AbstractAssetAttribute attribute) {
- this(asset, attribute, null, 0, false);
+ super(asset, attribute);
}
public AssetUpdate(Asset asset, AbstractAssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {
- this.attribute = attribute;
- this.id = asset.getId();
- this.name = asset.getName();
- if (asset.getPath() == null) {
- throw new IllegalArgumentException("Asset not loaded completely, empty path: " + asset);
- }
- this.pathFromRoot = asset.getReversePath(); // This is proving more useful than forward path
- this.typeString = asset.getType();
- this.type = asset.getWellKnownType();
- this.createdOn = asset.getCreatedOn();
- this.parentId = asset.getParentId();
- this.parentName = asset.getParentName();
- this.parentTypeString = asset.getParentType();
- this.parentType = asset.getParentType() != null ? AssetType.getByValue(asset.getParentType()) : null;
- this.realmId = asset.getRealmId();
- this.tenantRealm = asset.getTenantRealm();
- this.coordinates = asset.getCoordinates();
- this.oldValue = oldValue;
- this.oldValueTimestamp = oldValueTimestamp;
- this.northbound = northbound;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public String getId() {
- return id;
- }
-
- public String getName() {
- return name;
- }
-
- public String getTypeString() {
- return typeString;
- }
-
- public AssetType getType() {
- return type;
- }
-
- public String[] getPathFromRoot() {
- return pathFromRoot;
- }
-
- public String getParentId() {
- return parentId;
- }
-
- public String getParentName() {
- return parentName;
- }
-
- public String getParentTypeString() {
- return parentTypeString;
- }
-
- public AssetType getParentType() {
- return parentType;
- }
-
- public String getRealmId() {
- return realmId;
- }
-
- public String getTenantRealm() {
- return tenantRealm;
- }
-
- public double[] getCoordinates() {
- return coordinates;
- }
-
- public JsonValue getOldValue() {
- return oldValue;
- }
-
- public long getOldValueTimestamp() {
- return oldValueTimestamp;
+ super(asset, attribute, oldValue, oldValueTimestamp, northbound);
}
public Status getStatus() {
@@ -195,34 +78,10 @@ public class AssetUpdate {
return error;
}
- public boolean isNorthbound() {
- return northbound;
- }
-
- public JsonValue getValue() {
- return attribute.getValue();
- }
-
- public String getAttributeName() {
- return attribute.getName();
- }
-
- public long getValueTimestamp() {
- return attribute.getValueTimestamp();
- }
-
- public AttributeType getAttributeType() {
- return attribute.getType();
- }
-
public boolean isCompleted() {
return getStatus() == Status.COMPLETED;
}
- public boolean isValueChanged() {
- return !JsonUtil.equals(attribute.getValue(), oldValue);
- }
-
/////////////////////////////////////////////////////////////////
// GETTERS AND SETTERS BELOW CAN ONLY BE USED WHEN STATUS IS NOT COMPLETED
/////////////////////////////////////////////////////////////////
@@ -265,56 +124,4 @@ public class AssetUpdate {
throw new IllegalStateException("Instance is immutable, status '" + getStatus() + "': " + this);
}
}
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- AssetUpdate that = (AssetUpdate) o;
-
- // TODO Don't use jsEquals(), write own comparison by value
-
- return id.equals(that.id) &&
- getAttributeName().equalsIgnoreCase(that.getAttributeName()) &&
- JsonUtil.equals(getValue(), that.getValue()) &&
- getValueTimestamp() == that.getValueTimestamp() &&
- ((oldValue == null && that.oldValue == null) || (oldValue != null && JsonUtil.equals(oldValue, that.oldValue))) &&
- 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())
- + Long.hashCode(getValueTimestamp())
- + (oldValue != null ? JsonUtil.hashCode(oldValue) : 0) + Long.hashCode(oldValueTimestamp);
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "id='" + getId() + '\'' +
- ", name='" + getName()+ '\'' +
- ", typeString='" + getType()+ '\'' +
- ", attributeName='" + getAttributeName() + '\'' +
- ", attributeType=" + getAttributeType() +
- ", value='" + getValue().toJson() + '\'' +
- ", valueTimestamp=" + getValueTimestamp() +
- ", oldValue='" + (getOldValue() != null ? getOldValue().toJson() : "null") + '\'' +
- ", oldValueTimestamp=" + getOldValueTimestamp() +
- '}';
- }
}
diff --git a/model/src/main/java/org/openremote/model/rules/AssetEvent.java b/model/src/main/java/org/openremote/model/rules/AssetEvent.java
new file mode 100644
index 000000000..9ec072c5d
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/AssetEvent.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.rules;
+
+import org.kie.api.definition.type.Role;
+import org.openremote.model.asset.AbstractAssetUpdate;
+
+/**
+ * An asset attribute value change as a punctual event in rules processing.
+ */
[email protected](Role.Type.EVENT)
[email protected]("valueTimestamp")
+public class AssetEvent extends AbstractAssetUpdate {
+
+ public AssetEvent(AbstractAssetUpdate that) {
+ super(that);
+ }
+
+ public String getExpires() {
+ return attribute.getRulesEventExpires();
+ }
+}