100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Better error message when GlobalLock fails and increased timeout to 10 seconds, Syslog only logs org.openremote records, limit all firing of RulesEngine to guaranteed expiration time
Christian Bauerc1b33815a345
diff --git a/container/src/main/java/org/openremote/container/concurrent/GlobalLock.java b/container/src/main/java/org/openremote/container/concurrent/GlobalLock.javaindex f94f29247..d2434ac8b 100644--- a/container/src/main/java/org/openremote/container/concurrent/GlobalLock.java+++ b/container/src/main/java/org/openremote/container/concurrent/GlobalLock.java@@ -33,22 +33,57 @@ public class GlobalLock {private static final Logger LOG = Logger.getLogger(GlobalLock.class.getName());- // Provides exclusive access to shared protocol state- static protected final ReentrantLock lock = new ReentrantLock(true);+ /**+ * At least getOwner() is protected and not private...+ */+ static class CustomReentrantLock extends ReentrantLock {++ String info;++ public CustomReentrantLock() {+ super(true);+ }++ String owner() {+ Thread lockOwner;+ if ((lockOwner = super.getOwner()) != null) {+ return lockOwner.getName() + " executing " + info;+ }+ return "Unknown executing " + info;+ }++ public boolean tryLock(String info, long timeout, TimeUnit unit) throws InterruptedException {+ boolean result = super.tryLock(timeout, unit);+ if (result) {+ this.info = info;+ }+ return result;+ }++ @Override+ public void unlock() {+ super.unlock();+ info = null;+ }+ }++ // Provides exclusive access to shared state+ static protected final CustomReentrantLock lock = new CustomReentrantLock();protected GlobalLock() {}/**- * @return Defaults to 6 seconds, should be longer than it takes the router to be enabled/disabled.+ * @return Defaults to 10 seconds.*/static public int getLockTimeoutMillis() {- return 6000;+ return 10000;}/*** Obtain the lock within {@link #getLockTimeoutMillis()} or throw {@link IllegalStateException}.- * @param info An informal text that is printed in log messages.+ *+ * @param info An informal text that is printed in log messages.* @param runnable The guarded code to execute while holding the lock.*/static public void withLock(String info, Runnable runnable) {@@ -60,32 +95,31 @@ public class GlobalLock {/*** Obtain the lock within {@link #getLockTimeoutMillis()} or throw {@link IllegalStateException}.- * @param info An informal text that is printed in log messages.+ *+ * @param info An informal text that is printed in log messages.* @param supplier The guarded code to execute while holding the lock.*/static public <R> R withLockReturning(String info, Supplier<R> supplier) {try {- if (lock.tryLock(getLockTimeoutMillis(), TimeUnit.MILLISECONDS)) {- LOG.finest("+ Acquired lock on (count: " + lock.getHoldCount() + "): " + info);- // LOG.log(FINEST, "+ Acquired lock on (count: " + lock.getHoldCount() + "): " + info, new RuntimeException());- //LOG.finest("Lock on: " + Arrays.toString(Thread.currentThread().getStackTrace()));+ if (lock.tryLock(info, getLockTimeoutMillis(), TimeUnit.MILLISECONDS)) {+ LOG.finest("+ Acquired lock (count: " + lock.getHoldCount() + "): " + info);try {return supplier.get();} finally {- LOG.finest("- Releasing lock on (count: " + lock.getHoldCount() + "): " + info);+ LOG.finest("- Releasing lock (count: " + lock.getHoldCount() + "): " + info);if (!lock.isHeldByCurrentThread()) {- LOG.severe("Lock is held by another thread");+ LOG.severe("Lock is held by another thread, ensure the same thread acquires and releases the lock!");} else {lock.unlock();}}} else {throw new IllegalStateException(- "Could not acquire lock after waiting " + getLockTimeoutMillis() + "ms on: " + info+ "Could not acquire lock owned by " + lock.owner() + " after waiting " + getLockTimeoutMillis() + "ms: " + info);}} catch (InterruptedException ex) {- LOG.log(FINEST, "Interrupted while waiting for lock on: " + info);+ LOG.log(FINEST, "Interrupted while waiting for lock: " + info);return null;}}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 83a528cac..5e4c3cfa0 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -63,6 +63,7 @@ public class RulesEngine<T extends Ruleset> {final protected InferenceRulesEngine engine;protected boolean running;+ protected ScheduledFuture fireTimer;protected ScheduledFuture eventsTimer;protected ScheduledFuture statsTimer;@@ -259,72 +260,86 @@ public class RulesEngine<T extends Ruleset> {}public void fire() {- // Submit a task that fires the engine for all deployments- executorService.submit(() -> withLock(getClass().getSimpleName(), () -> {- if (!running) {- return;+ withLock(getClass().getSimpleName(), () -> {+ // Schedule a firing within the guaranteed expiration time (so not immediately), and+ // only if the last firing is done. This effectively limits how often the rules engine+ // will fire, only once within the guaranteed minimum expiration time.+ if (fireTimer == null || fireTimer.isDone()) {+ fireTimer = executorService.schedule(+ () -> withLock(getClass().getSimpleName(), this::fireAllDeployments),+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS+ );}+ });+ }- // Set the current clock- RulesClock clock = new RulesClock(timerService);- facts.setClock(clock);+ protected void fireAllDeployments() {+ if (!running) {+ return;+ }- // Remove any expired temporary facts- boolean factsExpired = facts.removeExpiredTemporaryFacts();+ // Set the current clock+ RulesClock clock = new RulesClock(timerService);+ facts.setClock(clock);- // TODO Optimize if scheduled firing of rules becomes a performance problem:- // Add fire(scheduledFiring) boolean- // Add enableTimer() as rule declaration option, each rule which uses time windows must set it- // Only fire if factsExpired || deployment.isAnyRuleEnabledTimer()- // Rules could default to enableTimer(true) and they could reduce firing frequency with enableTimer("1m")+ // Remove any expired temporary facts+ boolean factsExpired = facts.removeExpiredTemporaryFacts();- for (RulesetDeployment deployment : deployments.values()) {- try {- RULES_LOG.fine("Firing rules @" + clock + " of: " + deployment);+ // TODO Optimize if scheduled firing of rules becomes a performance problem:+ // Add fire(scheduledFiring) boolean+ // Add enableTimer() as rule declaration option, each rule which uses time windows must set it+ // Only fire if factsExpired || deployment.isAnyRuleEnabledTimer()+ // Rules could default to enableTimer(true) and they could reduce firing frequency with enableTimer("1m")- // If full detail logging is enabled- if (RULES_LOG.isLoggable(Level.FINEST)) {- // Log asset states and events before firing (note that this will log at INFO)- facts.logFacts(RULES_LOG);- }+ for (RulesetDeployment deployment : deployments.values()) {+ try {+ RULES_LOG.fine("Firing rules @" + clock + " of: " + deployment);- facts.resetTriggerCount();- long startTimestamp = System.currentTimeMillis();- engine.fire(deployment.getRules(), facts);- RULES_LOG.fine("Rules processing time: " + (System.currentTimeMillis() - startTimestamp) + "ms");+ // If full detail logging is enabled+ if (RULES_LOG.isLoggable(Level.FINEST)) {+ // Log asset states and events before firing (note that this will log at INFO)+ facts.logFacts(RULES_LOG);+ }- } catch (Exception ex) {- LOG.log(Level.SEVERE, "On " + RulesEngine.this + ", error firing rules of: " + deployment, ex);+ // Reset facts for this firing (loop detection etc.)+ facts.reset();- deployment.setStatus(EXECUTION_ERROR);- deployment.setError(ex);+ long startTimestamp = System.currentTimeMillis();+ engine.fire(deployment.getRules(), facts);+ RULES_LOG.fine("Rules executed in: " + (System.currentTimeMillis() - startTimestamp) + "ms");- // TODO We always stop on any error, good idea?- // TODO We only get here on LHS runtime errors, RHS runtime errors are in RuleFacts.onFailure()- stop();+ } catch (Exception ex) {+ LOG.log(Level.SEVERE, "On " + RulesEngine.this + ", error firing rules of: " + deployment, ex);- // TODO We skip any other deployment when we hit the first error, good idea?- break;- } finally {- facts.resetTriggerCount();- }- }+ deployment.setStatus(EXECUTION_ERROR);+ deployment.setError(ex);- // If we still have temporary facts, schedule a new firing so expired facts are removed eventually- if (facts.hasTemporaryFacts() && eventsTimer == null && !disableTemporaryFactExpiration) {- LOG.fine("Temporary facts present, scheduling new firing of rules on: " + this);- eventsTimer = executorService.scheduleAtFixedRate(- this::fire,- TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS,- TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS,- TimeUnit.MILLISECONDS- );- } else if (!facts.hasTemporaryFacts() && eventsTimer != null) {- LOG.fine("No temporary facts present, cancel scheduled firing of rules on: " + this);- eventsTimer.cancel(false);- eventsTimer = null;+ // TODO We always stop on any error, good idea?+ // TODO We only get here on LHS runtime errors, RHS runtime errors are in RuleFacts.onFailure()+ stop();++ // TODO We skip any other deployment when we hit the first error, good idea?+ break;+ } finally {+ // Reset facts after this firing (loop detection etc.)+ facts.reset();}- }));+ }++ // If we still have temporary facts, schedule a new firing so expired facts are removed eventually+ if (facts.hasTemporaryFacts() && eventsTimer == null && !disableTemporaryFactExpiration) {+ LOG.fine("Temporary facts present, scheduling new firing of rules on: " + this);+ eventsTimer = executorService.scheduleAtFixedRate(+ this::fire,+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS,+ TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS,+ TimeUnit.MILLISECONDS+ );+ } else if (!facts.hasTemporaryFacts() && eventsTimer != null) {+ LOG.fine("No temporary facts present, cancel scheduled firing of rules on: " + this);+ eventsTimer.cancel(false);+ eventsTimer = null;+ }}public void stop() {@@ -332,6 +347,10 @@ public class RulesEngine<T extends Ruleset> {return;}LOG.info("Stopping: " + this);+ if (fireTimer != null) {+ fireTimer.cancel(true);+ fireTimer = null;+ }if (eventsTimer != null) {eventsTimer.cancel(true);eventsTimer = null;diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex b95373311..0aa8e4667 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -19,7 +19,9 @@*/package org.openremote.manager.rules;-import org.jeasy.rules.api.*;+import org.jeasy.rules.api.Facts;+import org.jeasy.rules.api.Rule;+import org.jeasy.rules.api.RuleListener;import org.openremote.model.asset.AssetQuery;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeExecuteStatus;@@ -247,7 +249,7 @@ public class RulesFacts extends Facts implements RuleListener {/*** Reset rules triggered counter, used for loop detection.*/- public void resetTriggerCount() {+ public void reset() {triggerCount = 0;}diff --git a/model/src/main/java/org/openremote/model/rules/TemporaryFact.java b/model/src/main/java/org/openremote/model/rules/TemporaryFact.javaindex 4ed5d6863..f145c4774 100644--- a/model/src/main/java/org/openremote/model/rules/TemporaryFact.java+++ b/model/src/main/java/org/openremote/model/rules/TemporaryFact.java@@ -34,11 +34,11 @@ import java.time.temporal.ChronoUnit;public class TemporaryFact<T> extends Event {/**- * This value defines the periodic firing of the rules engines when temporary- * facts are present, and therefore has an impact on system load. If a temporary- * fact has a shorter expiration time, it's not guaranteed to be removed within- * that time. Any time-based operation, such as matching temporary facts in a- * sliding time window, must be designed with this margin in mind.+ * This value defines the periodic firing of the rules engines, and therefore+ * has an impact on system load. If a temporary fact has a shorter expiration+ * time, it's not guaranteed to be removed within that time. Any time-based+ * operation, such as matching temporary facts in a sliding time window, must+ * be designed with this margin in mind.*/public static final int GUARANTEED_MIN_EXPIRATION_MILLIS = 3000;diff --git a/model/src/main/java/org/openremote/model/syslog/SyslogCategory.java b/model/src/main/java/org/openremote/model/syslog/SyslogCategory.javaindex 1879342d9..c731b07bc 100644--- a/model/src/main/java/org/openremote/model/syslog/SyslogCategory.java+++ b/model/src/main/java/org/openremote/model/syslog/SyslogCategory.java@@ -100,6 +100,11 @@ public enum SyslogCategory {SyslogLevel level = SyslogLevel.getLevel(record.getLevel().intValue());if (level == null)return null;++ // Only log org.openremote records!+ if (!record.getLoggerName().startsWith("org.openremote"))+ return null;+for (SyslogCategory category : values()) {String loggerName = category.getLoggerName(record);if (loggerName != null) {