Skip to content

armgit / core

Public Imported from GitHub
0

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

Introduced GlobalLock to synchronize asset model/protocol/rules configuration and attribute event processing. Fixed bug with null datapoint value storage. Default rules lang is GROOVY. Added missing shutdown to VelbusProtocolTest.

Christian Bauerebd9aa8ddce1
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
index 7195278cb..d23119247 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
@@ -26,6 +26,7 @@ import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.agent.protocol.filter.MessageFilter;
import org.openremote.container.Container;
+import org.openremote.container.concurrent.GlobalLock;
import org.openremote.container.message.MessageBrokerContext;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
@@ -43,21 +44,20 @@ import org.openremote.model.value.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
-import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static java.util.logging.Level.FINEST;
+import static org.openremote.container.concurrent.GlobalLock.withLock;
+import static org.openremote.container.concurrent.GlobalLock.withLockReturning;
/**
* Thread-safe base implementation for protocols.
* <p>
- * Subclasses should use the {@link #withLock} and {@link #withLockReturning} methods
+ * Subclasses should use the {@link GlobalLock#withLock} and {@link GlobalLock#withLockReturning} methods
* to guard critical sections when modifying shared state:
* <blockquote><pre>{@code
- * withLock(() -> {
+ * withLock(getProtocolName(), () -> {
* // Critical section
* });
* }</pre></blockquote>
@@ -115,9 +115,6 @@ public abstract class AbstractProtocol implements Protocol {
protected ProtocolExecutorService executorService;
protected ProtocolAssetService assetService;
- // Provides exclusive access to shared protocol state
- protected final ReentrantLock lock = new ReentrantLock(true);
-
@Override
public void init(Container container) throws Exception {
LOG.info("Initializing protocol: " + getProtocolName());
@@ -132,7 +129,7 @@ public abstract class AbstractProtocol implements Protocol {
this.messageBrokerContext = container.getService(MessageBrokerSetupService.class).getContext();
this.producerTemplate = container.getService(MessageBrokerService.class).getProducerTemplate();
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
try {
messageBrokerContext.addRoutes(new RouteBuilder() {
@Override
@@ -155,7 +152,7 @@ public abstract class AbstractProtocol implements Protocol {
@Override
public void stop(Container container) throws Exception {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
linkedAttributes.clear();
try {
messageBrokerContext.stopRoute("Actuator-" + getProtocolName(), 1, TimeUnit.MILLISECONDS);
@@ -168,7 +165,7 @@ public abstract class AbstractProtocol implements Protocol {
@Override
public void linkProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<ConnectionStatus> statusConsumer) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
LOG.finer("Linking protocol configuration to protocol '" + getProtocolName() + "': " + protocolConfiguration);
linkedProtocolConfigurations.put(
protocolConfiguration.getReferenceOrThrow(),
@@ -180,7 +177,7 @@ public abstract class AbstractProtocol implements Protocol {
@Override
public void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
LOG.finer("Unlinking protocol configuration from protocol '" + getProtocolName() + "': " + protocolConfiguration);
doUnlinkProtocolConfiguration(protocolConfiguration);
linkedProtocolConfigurations.remove(protocolConfiguration.getReferenceOrThrow());
@@ -189,7 +186,7 @@ public abstract class AbstractProtocol implements Protocol {
@Override
public void linkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
attributes.forEach(attribute -> {
LOG.fine("Linking attribute to '" + getProtocolName() + "': " + attribute);
AttributeRef attributeRef = attribute.getReferenceOrThrow();
@@ -220,7 +217,7 @@ public abstract class AbstractProtocol implements Protocol {
@Override
public void unlinkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) throws Exception {
- withLock(() ->
+ withLock(getProtocolName(), () ->
attributes.forEach(attribute -> {
LOG.fine("Unlinking attribute on '" + getProtocolName() + "': " + attribute);
AttributeRef attributeRef = attribute.getReferenceOrThrow();
@@ -236,7 +233,7 @@ public abstract class AbstractProtocol implements Protocol {
* Gets a linked attribute by its attribute ref
*/
protected AssetAttribute getLinkedAttribute(AttributeRef attributeRef) {
- return withLockReturning(() -> linkedAttributes.get(attributeRef));
+ return withLockReturning(getProtocolName(), () -> linkedAttributes.get(attributeRef));
}
/**
@@ -248,7 +245,7 @@ public abstract class AbstractProtocol implements Protocol {
}
protected AssetAttribute getLinkedProtocolConfiguration(AttributeRef protocolConfigurationRef) {
- return withLockReturning(() -> {
+ return withLockReturning(getProtocolName(), () -> {
LinkedProtocolInfo linkedProtocolInfo = linkedProtocolConfigurations.get(protocolConfigurationRef);
// Don't bother with null check if someone calls here with an attribute not linked to this protocol
// then they're doing something wrong so fail hard and fast
@@ -258,7 +255,7 @@ public abstract class AbstractProtocol implements Protocol {
protected void processLinkedAttributeWrite(AttributeEvent event) {
LOG.finest("Processing linked attribute write on " + getProtocolName() + ": " + event);
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
AssetAttribute attribute = linkedAttributes.get(event.getAttributeRef());
if (attribute == null) {
LOG.warning("Attribute doesn't exist on this protocol: " + event.getAttributeRef());
@@ -283,7 +280,7 @@ public abstract class AbstractProtocol implements Protocol {
* publish new sensor values, which performs additional verification and uses a different messaging queue.
*/
protected void sendAttributeEvent(AttributeEvent event) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
// Don't allow updating linked attributes with this mechanism as it could cause an infinite loop
if (linkedAttributes.containsKey(event.getAttributeRef())) {
LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that: " + event);
@@ -300,7 +297,7 @@ public abstract class AbstractProtocol implements Protocol {
*/
@SuppressWarnings("unchecked")
protected void updateLinkedAttribute(final AttributeState finalState, long timestamp) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
AttributeState state = finalState;
AssetAttribute attribute = linkedAttributes.get(state.getAttributeRef());
@@ -406,7 +403,7 @@ public abstract class AbstractProtocol implements Protocol {
}
protected void updateAssetLocation(String assetId, Point location) {
- withLock(() -> assetService.updateAssetLocation(assetId, location));
+ withLock(getProtocolName(), () -> assetService.updateAssetLocation(assetId, location));
}
/**
@@ -415,7 +412,7 @@ public abstract class AbstractProtocol implements Protocol {
* the consumer to perform the modification.
*/
protected void updateLinkedProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<AssetAttribute> protocolUpdater) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
// Clone the protocol configuration rather than modify this one
AssetAttribute modifiedProtocolConfiguration = protocolConfiguration.deepCopy();
protocolUpdater.accept(modifiedProtocolConfiguration);
@@ -427,9 +424,10 @@ public abstract class AbstractProtocol implements Protocol {
* Update the runtime status of a protocol configuration by its attribute ref
*/
protected void updateStatus(AttributeRef protocolRef, ConnectionStatus connectionStatus) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
LinkedProtocolInfo protocolInfo = linkedProtocolConfigurations.get(protocolRef);
if (protocolInfo != null) {
+ LOG.fine("Updating protocol status to '" + connectionStatus + "': " + protocolRef);
protocolInfo.getConnectionStatusConsumer().accept(connectionStatus);
protocolInfo.setCurrentConnectionStatus(connectionStatus);
}
@@ -440,7 +438,7 @@ public abstract class AbstractProtocol implements Protocol {
* Gets the current runtime status of a protocol configuration.
*/
protected ConnectionStatus getStatus(AssetAttribute protocolConfiguration) {
- return withLockReturning(() -> {
+ return withLockReturning(getProtocolName(), () -> {
LinkedProtocolInfo linkedProtocolInfo = linkedProtocolConfigurations.get(protocolConfiguration.getReferenceOrThrow());
return linkedProtocolInfo.getCurrentConnectionStatus();
});
@@ -480,38 +478,6 @@ public abstract class AbstractProtocol implements Protocol {
return result;
}
- /**
- * @return Defaults to 6 seconds, should be longer than it takes the router to be enabled/disabled.
- */
- protected int getLockTimeoutMillis() {
- return 6000;
- }
-
- protected void withLock(Runnable runnable) {
- withLockReturning(() -> {
- runnable.run();
- return null;
- });
- }
-
- protected <R> R withLockReturning(Supplier<R> supplier) {
- try {
- if (lock.tryLock(getLockTimeoutMillis(), TimeUnit.MILLISECONDS)) {
- LOG.finest("+ Acquired lock on: " + getProtocolName());
- return supplier.get();
- } else {
- throw new IllegalStateException(
- "Could not acquire lock after waiting " + getLockTimeoutMillis() + "ms on: " + getProtocolName()
- );
- }
- } catch (InterruptedException ex) {
- LOG.log(FINEST, "Interrupted while waiting for lock on: " + getProtocolName());
- return null;
- } finally {
- LOG.finest("- Releasing lock on: " + getProtocolName());
- lock.unlock();
- }
- }
@Override
public String toString() {
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
index c6bfba893..14f7e4652 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
@@ -53,6 +53,7 @@ import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
/**
@@ -919,7 +920,7 @@ public class HttpClientProtocol extends AbstractProtocol {
}
protected void cancelPolling(AttributeRef attributeRef) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
ScheduledFuture pingPoll = pollingMap.remove(attributeRef);
if (pingPoll != null) {
pingPoll.cancel(false);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
index 941910255..57f7d3d3d 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
@@ -38,6 +38,8 @@ import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.stream.Collectors;
+import static org.openremote.container.concurrent.GlobalLock.withLock;
+import static org.openremote.container.concurrent.GlobalLock.withLockReturning;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
import static org.openremote.model.asset.AssetMeta.RANGE_MAX;
import static org.openremote.model.asset.AssetMeta.RANGE_MIN;
@@ -314,7 +316,7 @@ public class SimulatorProtocol extends AbstractProtocol {
* Call this to simulate a sensor update after the specified delay (it uses the last value supplied from send to actuator).
*/
public void updateSensor(AttributeRef attributeRef, int updateSensorDelayMilliseconds) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
AttributeRef instanceRef = attributeInstanceMap.get(attributeRef);
if (instanceRef == null) {
@@ -369,7 +371,7 @@ public class SimulatorProtocol extends AbstractProtocol {
* Call this to simulate a send to actuator.
*/
public boolean putValue(AttributeState attributeState) {
- return withLockReturning(() -> {
+ Boolean result = withLockReturning(getProtocolName(), () -> {
AttributeRef attributeRef = attributeState.getAttributeRef();
AttributeRef instanceRef = attributeInstanceMap.get(attributeRef);
@@ -413,6 +415,7 @@ public class SimulatorProtocol extends AbstractProtocol {
return true;
});
+ return result != null ? result : false;
}
/**
@@ -426,7 +429,7 @@ public class SimulatorProtocol extends AbstractProtocol {
* Call this to get the current value of an attribute.
*/
public Optional<Value> getValue(AttributeRef attributeRef) {
- return withLockReturning(() -> {
+ return withLockReturning(getProtocolName(), () -> {
SimulatorElement element = elements.get(attributeRef);
return element != null ? element.getValue() : Optional.empty();
});
@@ -450,7 +453,7 @@ public class SimulatorProtocol extends AbstractProtocol {
* Read a state snapshot.
*/
public Optional<SimulatorState> getSimulatorState(AttributeRef protocolConfigurationRef) {
- return withLockReturning(() -> {
+ return withLockReturning(getProtocolName(), () -> {
LOG.info("Getting simulator state for protocol configuration: " + protocolConfigurationRef);
if (!instances.containsKey(protocolConfigurationRef))
return Optional.empty();
@@ -469,7 +472,7 @@ public class SimulatorProtocol extends AbstractProtocol {
* Write a state snapshot.
*/
public void updateSimulatorState(SimulatorState simulatorState) {
- withLock(() -> {
+ withLock(getProtocolName(), () -> {
AttributeRef protocolConfigurationRef = simulatorState.getProtocolConfigurationRef();
if (!instances.containsKey(protocolConfigurationRef)) {
LOG.info("Ignoring simulator update, no instance for protocol configuration: " + protocolConfigurationRef);
diff --git a/container/src/main/java/org/openremote/container/concurrent/GlobalLock.java b/container/src/main/java/org/openremote/container/concurrent/GlobalLock.java
new file mode 100644
index 000000000..f94f29247
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/concurrent/GlobalLock.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2018, 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.container.concurrent;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Supplier;
+import java.util.logging.Logger;
+
+import static java.util.logging.Level.FINEST;
+
+/**
+ * A global reentrant exclusive lock, use convenience methods {@link #withLock} and {@link #withLockReturning}.
+ */
+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);
+
+ protected GlobalLock() {
+ }
+
+ /**
+ * @return Defaults to 6 seconds, should be longer than it takes the router to be enabled/disabled.
+ */
+ static public int getLockTimeoutMillis() {
+ return 6000;
+ }
+
+ /**
+ * Obtain the lock within {@link #getLockTimeoutMillis()} or throw {@link IllegalStateException}.
+ * @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) {
+ withLockReturning(info, () -> {
+ runnable.run();
+ return null;
+ });
+ }
+
+ /**
+ * Obtain the lock within {@link #getLockTimeoutMillis()} or throw {@link IllegalStateException}.
+ * @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()));
+ try {
+ return supplier.get();
+ } finally {
+ LOG.finest("- Releasing lock on (count: " + lock.getHoldCount() + "): " + info);
+ if (!lock.isHeldByCurrentThread()) {
+ LOG.severe("Lock is held by another thread");
+ } else {
+ lock.unlock();
+ }
+ }
+ } else {
+ throw new IllegalStateException(
+ "Could not acquire lock after waiting " + getLockTimeoutMillis() + "ms on: " + info
+ );
+ }
+ } catch (InterruptedException ex) {
+ LOG.log(FINEST, "Interrupted while waiting for lock on: " + info);
+ return null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
index 3002026d4..2d9aa4c01 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
@@ -25,6 +25,7 @@ import org.openremote.agent.protocol.Protocol;
import org.openremote.agent.protocol.ProtocolAssetService;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
+import org.openremote.container.concurrent.GlobalLock;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
@@ -54,6 +55,8 @@ import java.util.stream.Stream;
import static org.openremote.agent.protocol.Protocol.ACTUATOR_TOPIC;
import static org.openremote.agent.protocol.Protocol.SENSOR_QUEUE;
+import static org.openremote.container.concurrent.GlobalLock.withLock;
+import static org.openremote.container.concurrent.GlobalLock.withLockReturning;
import static org.openremote.container.persistence.PersistenceEvent.*;
import static org.openremote.manager.asset.AssetProcessingService.ASSET_QUEUE;
import static org.openremote.model.AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME;
@@ -88,6 +91,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
protected LocalAgentConnector localAgentConnector;
protected Map<String, Asset> agentMap;
+
@Override
public void init(Container container) throws Exception {
timerService = container.getService(TimerService.class);
@@ -431,115 +435,111 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
}
protected void linkProtocolConfigurations(Stream<AssetAttribute> configurations) {
- synchronized (protocolConfigurations) {
- configurations.forEach(configuration -> {
- AttributeRef protocolAttributeRef = configuration.getReferenceOrThrow();
- Protocol protocol = getProtocol(configuration);
+ withLock(getClass().getSimpleName(), () -> configurations.forEach(configuration -> {
+ AttributeRef protocolAttributeRef = configuration.getReferenceOrThrow();
+ Protocol protocol = getProtocol(configuration);
- if (protocol == null) {
- LOG.warning("Cannot find protocol that attribute is linked to: " + protocolAttributeRef);
- return;
- }
+ if (protocol == null) {
+ LOG.warning("Cannot find protocol that attribute is linked to: " + protocolAttributeRef);
+ return;
+ }
- // Create a consumer callback for deployment status updates
- Consumer<ConnectionStatus> deploymentStatusConsumer = status ->
- publishProtocolConnectionStatus(protocolAttributeRef, status);
+ // Store the info
+ protocolConfigurations.put(protocolAttributeRef, new Pair<>(configuration, null));
- // Store the info
- protocolConfigurations.put(protocolAttributeRef, new Pair<>(configuration, null));
+ // Create a consumer callback for protocol status updates
+ Consumer<ConnectionStatus> deploymentStatusConsumer = status ->
+ publishProtocolConnectionStatus(protocolAttributeRef, status);
- // Set status to linking
- publishProtocolConnectionStatus(protocolAttributeRef, CONNECTING);
+ // Set status to WAITING (we don't know what the protocol's status will be after linking configuration)
+ publishProtocolConnectionStatus(protocolAttributeRef, WAITING);
- // Link the protocol configuration to the protocol
- try {
- protocol.linkProtocolConfiguration(configuration, deploymentStatusConsumer);
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration linking", e);
- // Set status to error
- publishProtocolConnectionStatus(protocolAttributeRef, ERROR_CONFIGURATION);
- }
+ // Link the protocol configuration to the protocol
+ try {
+ protocol.linkProtocolConfiguration(configuration, deploymentStatusConsumer);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration linking", e);
+ // Set status to error
+ publishProtocolConnectionStatus(protocolAttributeRef, ERROR_CONFIGURATION);
+ }
- // Check protocol status and only continue linking attributes if not in error state
- ConnectionStatus connectionStatus = getProtocolConnectionStatus(protocolAttributeRef);
- if (connectionStatus == ERROR_CONFIGURATION || connectionStatus == ERROR) {
- LOG.warning("Protocol connection status is showing error so not linking attributes: " + configuration);
- return;
- }
+ // Check protocol status and only continue linking attributes if not in error state
+ ConnectionStatus connectionStatus = getProtocolConnectionStatus(protocolAttributeRef);
+ if (connectionStatus == ERROR_CONFIGURATION || connectionStatus == ERROR) {
+ LOG.warning("Protocol connection status is showing error so not linking attributes: " + configuration);
+ return;
+ }
- // Get all assets that have attributes that use this protocol configuration
- List<ServerAsset> assets = assetStorageService.findAll(
- new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ALL))
- .attributeMeta(
- new AssetQuery.AttributeRefPredicate(
- AssetMeta.AGENT_LINK,
- protocolAttributeRef.getEntityId(),
- protocolAttributeRef.getAttributeName()
- )
+ // Get all assets that have attributes that use this protocol configuration
+ List<ServerAsset> assets = assetStorageService.findAll(
+ new AssetQuery()
+ .select(new AssetQuery.Select(AssetQuery.Include.ALL))
+ .attributeMeta(
+ new AssetQuery.AttributeRefPredicate(
+ AssetMeta.AGENT_LINK,
+ protocolAttributeRef.getEntityId(),
+ protocolAttributeRef.getAttributeName()
)
- );
+ )
+ );
- assets.forEach(
- asset ->
- getGroupedAgentLinkAttributes(
- asset.getAttributesStream(),
- assetAttribute -> getAgentLink(assetAttribute)
- .map(attributeRef -> attributeRef.equals(protocolAttributeRef))
- .orElse(false),
- attribute -> LOG.warning("Linked protocol configuration not found: " + attribute)
- ).forEach(this::linkAttributes)
- );
- });
- }
+ assets.forEach(
+ asset ->
+ getGroupedAgentLinkAttributes(
+ asset.getAttributesStream(),
+ assetAttribute -> getAgentLink(assetAttribute)
+ .map(attributeRef -> attributeRef.equals(protocolAttributeRef))
+ .orElse(false),
+ attribute -> LOG.warning("Linked protocol configuration not found: " + attribute)
+ ).forEach(this::linkAttributes)
+ );
+ }));
}
protected void unlinkProtocolConfigurations(Stream<AssetAttribute> configurations) {
- synchronized (protocolConfigurations) {
- configurations.forEach(configuration -> {
- AttributeRef protocolAttributeRef = configuration.getReferenceOrThrow();
-
- // Get all assets that have attributes that use this protocol configuration
- List<ServerAsset> assets = assetStorageService.findAll(
- new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ALL))
- .attributeMeta(
- new AssetQuery.AttributeRefPredicate(
- AssetMeta.AGENT_LINK,
- protocolAttributeRef.getEntityId(),
- protocolAttributeRef.getAttributeName()
- )
+ withLock(getClass().getSimpleName(), () -> configurations.forEach(configuration -> {
+ AttributeRef protocolAttributeRef = configuration.getReferenceOrThrow();
+
+ // Get all assets that have attributes that use this protocol configuration
+ List<ServerAsset> assets = assetStorageService.findAll(
+ new AssetQuery()
+ .select(new AssetQuery.Select(AssetQuery.Include.ALL))
+ .attributeMeta(
+ new AssetQuery.AttributeRefPredicate(
+ AssetMeta.AGENT_LINK,
+ protocolAttributeRef.getEntityId(),
+ protocolAttributeRef.getAttributeName()
)
- );
+ )
+ );
- assets.forEach(
- asset ->
- getGroupedAgentLinkAttributes(
- asset.getAttributesStream(),
- assetAttribute -> getAgentLink(assetAttribute)
- .map(attributeRef -> attributeRef.equals(protocolAttributeRef))
- .orElse(false)
- ).forEach(this::unlinkAttributes)
- );
+ assets.forEach(
+ asset ->
+ getGroupedAgentLinkAttributes(
+ asset.getAttributesStream(),
+ assetAttribute -> getAgentLink(assetAttribute)
+ .map(attributeRef -> attributeRef.equals(protocolAttributeRef))
+ .orElse(false)
+ ).forEach(this::unlinkAttributes)
+ );
- Protocol protocol = getProtocol(configuration);
+ Protocol protocol = getProtocol(configuration);
- // Unlink the protocol configuration from the protocol
- try {
- protocol.unlinkProtocolConfiguration(configuration);
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration unlinking", e);
- }
+ // Unlink the protocol configuration from the protocol
+ try {
+ protocol.unlinkProtocolConfiguration(configuration);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration unlinking", e);
+ }
- // Set status to disconnected
- publishProtocolConnectionStatus(protocolAttributeRef, DISCONNECTED);
- protocolConfigurations.remove(protocolAttributeRef);
- });
- }
+ // Set status to disconnected
+ publishProtocolConnectionStatus(protocolAttributeRef, DISCONNECTED);
+ protocolConfigurations.remove(protocolAttributeRef);
+ }));
}
protected void publishProtocolConnectionStatus(AttributeRef protocolRef, ConnectionStatus connectionStatus) {
- synchronized (protocolConfigurations) {
+ withLock(getClass().getSimpleName(), () -> {
Pair<AssetAttribute, ConnectionStatus> protocolDeploymentInfo = protocolConfigurations.get(protocolRef);
if (protocolDeploymentInfo != null && protocolDeploymentInfo.value != connectionStatus) {
LOG.info("Agent protocol status updated to " + connectionStatus + ": " + protocolRef);
@@ -555,15 +555,14 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
)
);
}
- }
+ });
}
public ConnectionStatus getProtocolConnectionStatus(AttributeRef protocolRef) {
- synchronized (protocolConfigurations) {
- return Optional.ofNullable(protocolConfigurations.get(protocolRef))
+ return withLockReturning(getClass().getSimpleName(), () ->
+ Optional.ofNullable(protocolConfigurations.get(protocolRef))
.map(pair -> pair.value)
- .orElse(null);
- }
+ .orElse(null));
}
protected Protocol getProtocol(AssetAttribute protocolConfiguration) {
@@ -571,51 +570,51 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
}
protected void linkAttributes(AssetAttribute protocolConfiguration, Collection<AssetAttribute> attributes) {
- LOG.fine("Linking all attributes that use protocol attribute: " + protocolConfiguration);
- Protocol protocol = getProtocol(protocolConfiguration);
+ withLock(getClass().getSimpleName(), () -> {
+ LOG.fine("Linking all attributes that use protocol attribute: " + protocolConfiguration);
+ Protocol protocol = getProtocol(protocolConfiguration);
- if (protocol == null) {
- LOG.severe("Cannot link protocol attributes as protocol is null: " + protocolConfiguration);
- return;
- }
+ if (protocol == null) {
+ LOG.severe("Cannot link protocol attributes as protocol is null: " + protocolConfiguration);
+ return;
+ }
- synchronized (linkedAttributes) {
attributes.removeIf(attr -> linkedAttributes.contains(attr.getReferenceOrThrow()));
linkedAttributes.addAll(attributes.stream().map(AssetAttribute::getReferenceOrThrow).collect(Collectors.toList()));
- }
- try {
- LOG.finest("Linking protocol attributes to: " + protocol.getProtocolName());
- protocol.linkAttributes(attributes, protocolConfiguration);
- } catch (Exception ex) {
- LOG.log(Level.SEVERE, "Ignoring error on linking attributes to protocol: " + protocol.getProtocolName(), ex);
- // Update the status of this protocol configuration to error
- publishProtocolConnectionStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);
- }
+ try {
+ LOG.finest("Linking protocol attributes to: " + protocol.getProtocolName());
+ protocol.linkAttributes(attributes, protocolConfiguration);
+ } catch (Exception ex) {
+ LOG.log(Level.SEVERE, "Ignoring error on linking attributes to protocol: " + protocol.getProtocolName(), ex);
+ // Update the status of this protocol configuration to error
+ publishProtocolConnectionStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);
+ }
+ });
}
protected void unlinkAttributes(AssetAttribute protocolConfiguration, Collection<AssetAttribute> attributes) {
- LOG.fine("Unlinking all attributes that use protocol attribute: " + protocolConfiguration);
- Protocol protocol = getProtocol(protocolConfiguration);
+ withLock(getClass().getSimpleName(), () -> {
+ LOG.fine("Unlinking all attributes that use protocol attribute: " + protocolConfiguration);
+ Protocol protocol = getProtocol(protocolConfiguration);
- if (protocol == null) {
- LOG.severe("Cannot unlink protocol attributes as protocol is null: " + protocolConfiguration);
- return;
- }
+ if (protocol == null) {
+ LOG.severe("Cannot unlink protocol attributes as protocol is null: " + protocolConfiguration);
+ return;
+ }
- synchronized (linkedAttributes) {
attributes.removeIf(attr -> !linkedAttributes.contains(attr.getReferenceOrThrow()));
linkedAttributes.removeAll(attributes.stream().map(AssetAttribute::getReferenceOrThrow).collect(Collectors.toList()));
- }
- try {
- LOG.finest("Unlinking protocol attributes from: " + protocol.getProtocolName());
- protocol.unlinkAttributes(attributes, protocolConfiguration);
- } catch (Exception ex) {
- LOG.log(Level.SEVERE, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);
- // Update the status of this protocol configuration to error
- publishProtocolConnectionStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);
- }
+ try {
+ LOG.finest("Unlinking protocol attributes from: " + protocol.getProtocolName());
+ protocol.unlinkAttributes(attributes, protocolConfiguration);
+ } catch (Exception ex) {
+ LOG.log(Level.SEVERE, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);
+ // Update the status of this protocol configuration to error
+ publishProtocolConnectionStatus(protocolConfiguration.getReferenceOrThrow(), ERROR);
+ }
+ });
}
/**
@@ -635,8 +634,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
return false;
}
- synchronized (protocolConfigurations) {
- return AgentLink.getAgentLink(attribute)
+ Boolean result = withLockReturning(getClass().getSimpleName(), () ->
+ AgentLink.getAgentLink(attribute)
.map(ref ->
getProtocolConfiguration(ref)
.orElseThrow(() -> new AssetProcessingException(AssetProcessingException.Reason.INVALID_AGENT_LINK))
@@ -654,8 +653,9 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
});
return true; // Processing complete, skip other processors
})
- .orElse(false); // This is just a non protocol attribute so allow the processing to continue
- }
+ .orElse(false) // This is a regular attribute so allow the processing to continue
+ );
+ return result != null ? result : false;
}
/**
@@ -699,10 +699,10 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
}
public Optional<AssetAttribute> getProtocolConfiguration(AttributeRef protocolRef) {
- synchronized (protocolConfigurations) {
+ return withLockReturning(getClass().getSimpleName(), () -> {
Pair<AssetAttribute, ConnectionStatus> deploymentStatusPair = protocolConfigurations.get(protocolRef);
return deploymentStatusPair == null ? Optional.empty() : Optional.of(deploymentStatusPair.key);
- }
+ });
}
public Optional<AgentConnector> getAgentConnector(Asset agent) {
@@ -713,23 +713,25 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
return !Agent.hasUrl(agent) ? Optional.of(localAgentConnector) : Optional.empty();
}
- protected synchronized void addReplaceAgent(Asset agent) {
- getAgents().put(agent.getId(), agent);
+ protected void addReplaceAgent(Asset agent) {
+ withLock(getClass().getSimpleName(), () -> getAgents().put(agent.getId(), agent)
+ );
}
- protected synchronized void removeAgent(Asset agent) {
- getAgents().remove(agent.getId());
+ protected void removeAgent(Asset agent) {
+ withLock(getClass().getSimpleName(), () -> getAgents().remove(agent.getId()));
}
- public synchronized Map<String, Asset> getAgents() {
- if (agentMap == null) {
- agentMap = assetStorageService.findAll(new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ALL))
- .type(AssetType.AGENT))
- .stream()
- .collect(Collectors.toMap(Asset::getId, agent -> agent));
- }
-
- return agentMap;
+ public Map<String, Asset> getAgents() {
+ return withLockReturning(getClass().getSimpleName(), () -> {
+ if (agentMap == null) {
+ agentMap = assetStorageService.findAll(new AssetQuery()
+ .select(new AssetQuery.Select(AssetQuery.Include.ALL))
+ .type(AssetType.AGENT))
+ .stream()
+ .collect(Collectors.toMap(Asset::getId, agent -> agent));
+ }
+ return agentMap;
+ });
}
}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index d213777c7..a3e4d84fb 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -54,6 +54,7 @@ import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.manager.asset.AssetProcessingException.Reason.*;
import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;
import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
@@ -79,10 +80,7 @@ import static org.openremote.model.attribute.AttributeEvent.Source.*;
* at any point then an {@link AssetProcessingException} will be logged as a warning with an
* {@link AssetProcessingException.Reason}.
* <p>
- * Once successfully validated the event is converted into an {@link AssetState} message which is then passed through
- * the processing chain of consumers.
- * <p>
- * The regular processing chain is:
+ * Once successfully validated a chain of {@link AssetUpdateProcessor}s is handling the update message:
* <ul>
* <li>{@link AgentService}</li>
* <li>{@link RulesService}</li>
@@ -102,22 +100,14 @@ import static org.openremote.model.attribute.AttributeEvent.Source.*;
* This means that a protocol implementation is responsible for producing a new {@link AttributeEvent} to
* indicate to the rules and database memory that the attribute value has/has not changed. The protocol should know
* best when to do this and it will vary from protocol to protocol; some 'things' might respond to an actuator write
- * immediately with a new sensor read, or they might send a later "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.
+ * immediately with a new sensor read, or they might send a later "sensor value changed" message or both or neither
+ * (the actuator is "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.
* <h2>Rules Service processing logic</h2>
* <p>
- * Checks if attribute is {@link AssetAttribute#isRuleState} and {@link AssetAttribute#isRuleEvent}, and if
+ * Checks if attribute is {@link AssetAttribute#isRuleState} and/or {@link AssetAttribute#isRuleEvent}, and if
* so the message is passed through the rule engines that are in scope for the asset.
* <p>
- * For {@link AssetState} messages, the rules service keeps the facts and thus the state of rule facts
- * are in sync with the asset state changes that occur. If an asset attribute value changes,
- * the {@link AssetState} in the rules engines will be updated to reflect the change.
- * <p>
- * For temporary {@link AssetState} event messages, they are inserted in the rules
- * engines in scope and expired automatically if the event lifetime set in
- * {@link RulesService#RULE_EVENT_EXPIRES} is reached, or if the event lifetime set in the
- * attribute {@link AssetMeta#RULE_EVENT_EXPIRES} is reached.
* <h2>Asset Storage Service processing logic</h2>
* <p>
* Always tries to persist the attribute value in the database and allows the message to continue if the commit was
@@ -249,10 +239,145 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
- Do we want JMS/AMQP/WSS or SOME_API/MQTT/WSS? ActiveMQ or Moquette?
*/
from(ASSET_QUEUE)
- .routeId("AssetUpdates")
+ .routeId("AssetQueueProcessor")
.filter(body().isInstanceOf(AttributeEvent.class))
.doTry()
- .process(processAttributeEvent())
+ // Lock the global context, we can only process attribute events when the
+ // context isn't locked. Agent- and RulesService lock the context while protocols
+ // or rulesets are modified.
+ .process(exchange -> withLock("AssetQueueProcessor", () -> {
+
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+ LOG.finest("Processing: " + event);
+ if (event.getEntityId() == null || event.getEntityId().isEmpty())
+ return;
+ if (event.getAttributeName() == null || event.getAttributeName().isEmpty())
+ return;
+ Source source = exchange.getIn().getHeader(HEADER_SOURCE, () -> null, Source.class);
+ if (source == null) {
+ throw new AssetProcessingException(MISSING_SOURCE);
+ }
+
+ // Process the asset update in a database transaction, this ensures that processors
+ // will see consistent database state and we only commit if no processor failed. This
+ // still won't make this procedure consistent with the message queue from which we consume!
+ persistenceService.doTransaction(em -> {
+ ServerAsset asset = assetStorageService.find(em, event.getEntityId(), true);
+ if (asset == null)
+ throw new AssetProcessingException(ASSET_NOT_FOUND);
+
+ AssetAttribute oldAttribute = asset.getAttribute(event.getAttributeName()).orElse(null);
+ if (oldAttribute == null)
+ throw new AssetProcessingException(ATTRIBUTE_NOT_FOUND);
+
+ // Agent attributes can't be updated with events
+ if (asset.getWellKnownType() == AssetType.AGENT) {
+ throw new AssetProcessingException(ILLEGAL_AGENT_UPDATE);
+ }
+
+ // For executable attributes, non-sensor sources can set a writable attribute execute status
+ if (oldAttribute.isExecutable() && source != SENSOR) {
+ Optional<AttributeExecuteStatus> status = event.getValue()
+ .flatMap(Values::getString)
+ .flatMap(AttributeExecuteStatus::fromString);
+
+ if (status.isPresent() && !status.get().isWrite()) {
+ throw new AssetProcessingException(INVALID_ATTRIBUTE_EXECUTE_STATUS);
+ }
+ }
+
+ switch (source) {
+ case CLIENT:
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+ if (authContext == null) {
+ throw new AssetProcessingException(NO_AUTH_CONTEXT);
+ }
+
+ // Check realm, must be accessible
+ if (!identityService.getIdentityProvider().isTenantActiveAndAccessible(authContext, asset)) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Check read-only
+ if (oldAttribute.isReadOnly() && !authContext.isSuperUser()) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Regular user must have write assets role
+ if (!authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Check restricted user
+ if (identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId())) {
+ // Must be asset linked to user
+ if (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+ // Must be writable by restricted client
+ if (!oldAttribute.isAccessRestrictedWrite()) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+ }
+ break;
+
+ case SENSOR:
+ Optional<AssetAttribute> protocolConfiguration =
+ getAgentLink(oldAttribute).flatMap(agentService::getProtocolConfiguration);
+
+ // Sensor event must be for an attribute linked to a protocol configuration
+ if (!protocolConfiguration.isPresent()) {
+ throw new AssetProcessingException(INVALID_AGENT_LINK);
+ }
+ break;
+ }
+
+ // Either use the timestamp of the event or set event time to processing time
+ long processingTime = timerService.getCurrentTimeMillis();
+ long eventTime = event.getTimestamp() > 0 ? event.getTimestamp() : processingTime;
+
+ // Ensure timestamp of event is not in the future as that would essentially block access to
+ // the attribute until after that time (maybe that is desirable behaviour)
+ if (eventTime - processingTime > 0) {
+ // TODO: Decide how to handle update events in the future - ignore or change timestamp
+ throw new AssetProcessingException(
+ EVENT_IN_FUTURE,
+ "current time: " + new Date(processingTime) + "/" + processingTime
+ + ", event time: " + new Date(eventTime) + "/" + eventTime
+ );
+ }
+
+ // Check the last update timestamp of the attribute, ignoring any event that is older than last update
+ // TODO This means we drop out-of-sequence events but accept events with the same source timestamp
+ // TODO Several attribute events can occur in the same millisecond, then order of application is undefined
+ oldAttribute.getValueTimestamp().filter(t -> t >= 0 && eventTime < t).ifPresent(
+ lastStateTime -> {
+ throw new AssetProcessingException(
+ EVENT_OUTDATED,
+ "last asset state time: " + new Date(lastStateTime) + "/" + lastStateTime
+ + ", event time: " + new Date(eventTime) + "/" + eventTime);
+ }
+ );
+
+ // Create a copy of the attribute and set the new value and timestamp
+ AssetAttribute updatedAttribute = oldAttribute.deepCopy();
+ updatedAttribute.setValue(event.getValue().orElse(null), eventTime);
+
+ // Validate constraints of attribute
+ List<ValidationFailure> validationFailures = updatedAttribute.getValidationFailures();
+ if (!validationFailures.isEmpty()) {
+ throw new AssetProcessingException(ATTRIBUTE_VALIDATION_FAILURE, validationFailures.toString());
+ }
+
+ // Push through all processors
+ boolean consumedCompletely = processAssetUpdate(em, asset, updatedAttribute, source);
+
+ // Publish a new event for clients if no processor consumed the update completely
+ if (!consumedCompletely) {
+ publishClientEvent(asset, updatedAttribute);
+ }
+ });
+ }))
.endDoTry()
.doCatch(AssetProcessingException.class)
.process(handleAssetProcessingException(LOG));
@@ -312,147 +437,14 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
if (!complete) {
LOG.finest("No processor consumed the update completely, storing: " + attribute);
- storeAttribute(em, asset, attribute);
+ storeAttributeValue(em, asset, attribute);
+ em.flush(); // Make sure constraint violations are immediately visible
}
LOG.fine("<<< Processing complete: " + attribute);
return complete;
}
- protected Processor processAttributeEvent() {
- return exchange -> {
- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
- if (event.getEntityId() == null || event.getEntityId().isEmpty())
- return;
- if (event.getAttributeName() == null || event.getAttributeName().isEmpty())
- return;
- Source source = exchange.getIn().getHeader(HEADER_SOURCE, () -> null, Source.class);
- if (source == null) {
- throw new AssetProcessingException(MISSING_SOURCE);
- }
-
- // Process the asset update in a database transaction, this ensures that processors
- // will see consistent database state and we only commit if no processor failed. This
- // still won't make this procedure consistent with the message queue from which we consume!
- persistenceService.doTransaction(em -> {
- ServerAsset asset = assetStorageService.find(em, event.getEntityId(), true);
- if (asset == null)
- throw new AssetProcessingException(ASSET_NOT_FOUND);
-
- AssetAttribute oldAttribute = asset.getAttribute(event.getAttributeName()).orElse(null);
- if (oldAttribute == null)
- throw new AssetProcessingException(ATTRIBUTE_NOT_FOUND);
-
- // Agent attributes can't be updated with events
- if (asset.getWellKnownType() == AssetType.AGENT) {
- throw new AssetProcessingException(ILLEGAL_AGENT_UPDATE);
- }
-
- // For executable attributes, non-sensor sources can set a writable attribute execute status
- if (oldAttribute.isExecutable() && source != SENSOR) {
- Optional<AttributeExecuteStatus> status = event.getValue()
- .flatMap(Values::getString)
- .flatMap(AttributeExecuteStatus::fromString);
-
- if (status.isPresent() && !status.get().isWrite()) {
- throw new AssetProcessingException(INVALID_ATTRIBUTE_EXECUTE_STATUS);
- }
- }
-
- switch (source) {
- case CLIENT:
- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
- if (authContext == null) {
- throw new AssetProcessingException(NO_AUTH_CONTEXT);
- }
-
- // Check realm, must be accessible
- if (!identityService.getIdentityProvider().isTenantActiveAndAccessible(authContext, asset)) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // Check read-only
- if (oldAttribute.isReadOnly() && !authContext.isSuperUser()) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // Regular user must have write assets role
- if (!authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // Check restricted user
- if (identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId())) {
- // Must be asset linked to user
- if (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
- // Must be writable by restricted client
- if (!oldAttribute.isAccessRestrictedWrite()) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
- }
- break;
-
- case SENSOR:
- Optional<AssetAttribute> protocolConfiguration =
- getAgentLink(oldAttribute).flatMap(agentService::getProtocolConfiguration);
-
- // Sensor event must be for an attribute linked to a protocol configuration
- if (!protocolConfiguration.isPresent()) {
- throw new AssetProcessingException(INVALID_AGENT_LINK);
- }
- break;
- }
-
- // Either use the timestamp of the event or set event time to processing time
- long processingTime = timerService.getCurrentTimeMillis();
- long eventTime = event.getTimestamp() > 0 ? event.getTimestamp() : processingTime;
-
- // Ensure timestamp of event is not in the future as that would essentially block access to
- // the attribute until after that time (maybe that is desirable behaviour)
- if (eventTime - processingTime > 0) {
- // TODO: Decide how to handle update events in the future - ignore or change timestamp
- throw new AssetProcessingException(
- EVENT_IN_FUTURE,
- "current time: " + new Date(processingTime) + "/" + processingTime
- + ", event time: " + new Date(eventTime) + "/" + eventTime
- );
- }
-
- // Check the last update timestamp of the attribute, ignoring any event that is older than last update
- // TODO This means we drop out-of-sequence events but accept events with the same source timestamp
- // TODO Several attribute events can occur in the same millisecond, then order of application is undefined
- oldAttribute.getValueTimestamp().filter(t -> t >= 0 && eventTime < t).ifPresent(
- lastStateTime -> {
- throw new AssetProcessingException(
- EVENT_OUTDATED,
- "last asset state time: " + new Date(lastStateTime) + "/" + lastStateTime
- + ", event time: " + new Date(eventTime) + "/" + eventTime);
- }
- );
-
- // Create a copy of the attribute and set the new value and timestamp
- AssetAttribute updatedAttribute = oldAttribute.deepCopy();
- updatedAttribute.setValue(event.getValue().orElse(null), eventTime);
-
- // Validate constraints of attribute
- List<ValidationFailure> validationFailures = updatedAttribute.getValidationFailures();
- if (!validationFailures.isEmpty()) {
- throw new AssetProcessingException(ATTRIBUTE_VALIDATION_FAILURE, validationFailures.toString());
- }
-
- // Push through all processors
- boolean consumedCompletely = processAssetUpdate(em, asset, updatedAttribute, source);
-
- // Publish a new event for clients if no processor consumed the update completely
- if (!consumedCompletely) {
- publishClientEvent(asset, updatedAttribute);
- }
- });
- };
- }
-
protected static Processor handleAssetProcessingException(Logger logger) {
return exchange -> {
AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
@@ -486,7 +478,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
};
}
- protected void storeAttribute(EntityManager em, Asset asset, AssetAttribute attribute) throws AssetProcessingException {
+ protected void storeAttributeValue(EntityManager em, Asset asset, AssetAttribute attribute) throws AssetProcessingException {
String attributeName = attribute.getName()
.orElseThrow(() -> new AssetProcessingException(
STATE_STORAGE_FAILED,
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index af9cab84d..3c9cd7045 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -1142,7 +1142,10 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
statement.setString(6, attributeName);
int updatedRows = statement.executeUpdate();
- LOG.fine("Stored asset '" + assetId + "' attribute '" + attributeName + "' value, affected rows: " + updatedRows);
+ LOG.fine("Stored asset '" + assetId
+ + "' attribute '" + attributeName
+ + "' (affected rows: " + updatedRows + ") value: "
+ + (value != null ? value.toJson() : "null"));
return updatedRows == 1;
}
});
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java b/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java
index 7f4f5b9d7..0e2fefd66 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java
@@ -19,11 +19,20 @@
*/
package org.openremote.manager.asset;
+import org.openremote.container.concurrent.GlobalLock;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeEvent.Source;
import javax.persistence.EntityManager;
+/**
+ * Process update of an asset attribute (value), from a {@link Source}.
+ *
+ * Implementations don't have to lock the whole context through {@link GlobalLock}, the
+ * caller of this has already obtained the lock. Internal synchronization and thread-safety
+ * must still be maintained if shared state of a processor can be modified by concurrent tasks
+ * maintained by that processor.
+ */
public interface AssetUpdateProcessor {
/**
diff --git a/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java b/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java
index 0dabfef88..cd5822c66 100644
--- a/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java
+++ b/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java
@@ -54,7 +54,7 @@ public class ManagerExecutorService implements ProtocolExecutorService {
@Override
public void stop(Container container) throws Exception {
- scheduledTasksExecutor.shutdown();
+ scheduledTasksExecutor.shutdownNow();
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
index a633a813f..13205af94 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
@@ -68,7 +68,8 @@ public class AssetDatapointService implements ContainerService, AssetUpdateProce
Source source) throws AssetProcessingException {
if (Datapoint.isDatapointsCapable(attribute)
&& attribute.isStoreDatapoints()
- && attribute.getStateEvent().isPresent()) {
+ && attribute.getStateEvent().isPresent()
+ && attribute.getStateEvent().get().getValue().isPresent()) { // TODO Currently can't store datapoints with null value
LOG.finest("Storing datapoint for: " + attribute);
AssetDatapoint assetDatapoint = new AssetDatapoint(attribute.getStateEvent().get());
em.persist(assetDatapoint);
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index 60766ff6a..e8f95c229 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -37,6 +37,7 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.manager.rules.RulesetDeployment.Status.*;
public class RulesEngine<T extends Ruleset> {
@@ -102,67 +103,55 @@ public class RulesEngine<T extends Ruleset> {
* @return a shallow copy of the asset state facts.
*/
public Set<AssetState> getAssetStates() {
- synchronized (deployments) {
- return new HashSet<>(facts.getAssetStates());
- }
+ return new HashSet<>(facts.getAssetStates());
}
/**
* @return a shallow copy of the asset event facts.
*/
public List<TemporaryFact<AssetState>> getAssetEvents() {
- synchronized (deployments) {
- return new ArrayList<>(facts.getAssetEvents());
- }
+ return new ArrayList<>(facts.getAssetEvents());
}
public boolean isRunning() {
- synchronized (deployments) {
- return running;
- }
+ return running;
}
public boolean isError() {
- synchronized (deployments) {
- for (RulesetDeployment deployment : deployments.values()) {
- if (deployment.status == COMPILATION_ERROR || deployment.getStatus() == EXECUTION_ERROR) {
- return true;
- }
+ for (RulesetDeployment deployment : deployments.values()) {
+ if (deployment.status == COMPILATION_ERROR || deployment.getStatus() == EXECUTION_ERROR) {
+ return true;
}
- return false;
}
+ return false;
}
public RuntimeException getError() {
- synchronized (deployments) {
- List<RulesetDeployment> deploymentsWithCompilationError = new ArrayList<>();
- List<RulesetDeployment> deploymentsWithExecutionError = new ArrayList<>();
- for (RulesetDeployment deployment : deployments.values()) {
- if (deployment.getStatus() == COMPILATION_ERROR) {
- deploymentsWithCompilationError.add(deployment);
- } else if (deployment.getStatus() == EXECUTION_ERROR) {
- deploymentsWithExecutionError.add(deployment);
- }
- }
- if (deploymentsWithCompilationError.size() > 0 || deploymentsWithExecutionError.size() > 0) {
- return new RuntimeException(
- "Ruleset deployments have errors, failed compilation: "
- + deploymentsWithCompilationError.size()
- + ", failed execution: "
- + deploymentsWithExecutionError.size() + " - on: " + this
- );
+ List<RulesetDeployment> deploymentsWithCompilationError = new ArrayList<>();
+ List<RulesetDeployment> deploymentsWithExecutionError = new ArrayList<>();
+ for (RulesetDeployment deployment : deployments.values()) {
+ if (deployment.getStatus() == COMPILATION_ERROR) {
+ deploymentsWithCompilationError.add(deployment);
+ } else if (deployment.getStatus() == EXECUTION_ERROR) {
+ deploymentsWithExecutionError.add(deployment);
}
- return null;
}
+ if (deploymentsWithCompilationError.size() > 0 || deploymentsWithExecutionError.size() > 0) {
+ return new RuntimeException(
+ "Ruleset deployments have errors, failed compilation: "
+ + deploymentsWithCompilationError.size()
+ + ", failed execution: "
+ + deploymentsWithExecutionError.size() + " - on: " + this
+ );
+ }
+ return null;
}
/**
* @return <code>true</code> if all rulesets are {@link RulesetDeployment.Status#DEPLOYED} and this engine can be started.
*/
public boolean isDeployed() {
- synchronized (deployments) {
- return deployments.values().stream().allMatch(rd -> rd.getStatus() == DEPLOYED);
- }
+ return deployments.values().stream().allMatch(rd -> rd.getStatus() == DEPLOYED);
}
public void addRuleset(T ruleset) {
@@ -172,216 +161,199 @@ public class RulesEngine<T extends Ruleset> {
return;
}
- synchronized (deployments) {
- RulesetDeployment deployment = deployments.get(ruleset.getId());
+ RulesetDeployment deployment = deployments.get(ruleset.getId());
- stop();
+ stop();
- // Check if ruleset is already deployed (maybe an older version)
- if (deployment != null) {
- LOG.info("Removing ruleset deployment: " + ruleset);
- deployments.remove(ruleset.getId());
- updateDeploymentInfo();
- }
+ // Check if ruleset is already deployed (maybe an older version)
+ if (deployment != null) {
+ LOG.info("Removing ruleset deployment: " + ruleset);
+ deployments.remove(ruleset.getId());
+ updateDeploymentInfo();
+ }
- deployment = new RulesetDeployment(ruleset.getId(), ruleset.getName(), ruleset.getVersion());
+ deployment = new RulesetDeployment(ruleset.getId(), ruleset.getName(), ruleset.getVersion());
- boolean compilationSuccessful = deployment.registerRules(ruleset, assetsFacade, usersFacade);
+ boolean compilationSuccessful = deployment.registerRules(ruleset, assetsFacade, usersFacade);
- if (!compilationSuccessful) {
- // If any other ruleset is DEPLOYED in this scope, demote to READY
- for (RulesetDeployment rd : deployments.values()) {
- if (rd.getStatus() == DEPLOYED) {
- rd.setStatus(READY);
- }
+ if (!compilationSuccessful) {
+ // If any other ruleset is DEPLOYED in this scope, demote to READY
+ for (RulesetDeployment rd : deployments.values()) {
+ if (rd.getStatus() == DEPLOYED) {
+ rd.setStatus(READY);
}
}
+ }
- // Add new ruleset and set its status to either DEPLOYED or COMPILATION_ERROR
- deployment.setStatus(compilationSuccessful ? DEPLOYED : COMPILATION_ERROR);
- deployments.put(ruleset.getId(), deployment);
- updateDeploymentInfo();
+ // Add new ruleset and set its status to either DEPLOYED or COMPILATION_ERROR
+ deployment.setStatus(compilationSuccessful ? DEPLOYED : COMPILATION_ERROR);
+ deployments.put(ruleset.getId(), deployment);
+ updateDeploymentInfo();
- start();
- }
+ start();
}
/**
* @return <code>true</code> if this rules engine has no deployments.
*/
public boolean removeRuleset(Ruleset ruleset) {
- synchronized (deployments) {
- if (!deployments.containsKey(ruleset.getId())) {
- LOG.finer("Ruleset cannot be retracted as it was never deployed: " + ruleset);
- return deployments.size() == 0;
- }
+ if (!deployments.containsKey(ruleset.getId())) {
+ LOG.finer("Ruleset cannot be retracted as it was never deployed: " + ruleset);
+ return deployments.size() == 0;
+ }
- stop();
+ stop();
- deployments.remove(ruleset.getId());
- updateDeploymentInfo();
+ deployments.remove(ruleset.getId());
+ updateDeploymentInfo();
- // If there are no deployments with COMPILATION_ERROR, promote all which are READY to DEPLOYED
- boolean anyDeploymentsHaveCompilationError = deployments
- .values()
- .stream()
- .anyMatch(rd -> rd.getStatus() == COMPILATION_ERROR);
+ // If there are no deployments with COMPILATION_ERROR, promote all which are READY to DEPLOYED
+ boolean anyDeploymentsHaveCompilationError = deployments
+ .values()
+ .stream()
+ .anyMatch(rd -> rd.getStatus() == COMPILATION_ERROR);
- if (!anyDeploymentsHaveCompilationError) {
- deployments.values().forEach(rd -> {
- if (rd.getStatus() == READY) {
- rd.setStatus(DEPLOYED);
- }
- });
- }
+ if (!anyDeploymentsHaveCompilationError) {
+ deployments.values().forEach(rd -> {
+ if (rd.getStatus() == READY) {
+ rd.setStatus(DEPLOYED);
+ }
+ });
+ }
- if (deployments.size() > 0) {
- start();
- return false;
- } else {
- return true;
- }
+ if (deployments.size() > 0) {
+ start();
+ return false;
+ } else {
+ return true;
}
}
public void start() {
- synchronized (deployments) {
- if (isRunning()) {
- return;
- }
+ if (isRunning()) {
+ return;
+ }
- if (!isDeployed()) {
- LOG.fine("Cannot start rules engine, not all rulesets are status " + DEPLOYED);
- return;
- }
+ if (!isDeployed()) {
+ LOG.fine("Cannot start rules engine, not all rulesets are status " + DEPLOYED);
+ return;
+ }
- if (deployments.size() == 0) {
- LOG.finest("No rulesets so nothing to start");
- return;
- }
+ if (deployments.size() == 0) {
+ LOG.finest("No rulesets so nothing to start");
+ return;
+ }
- LOG.info("Starting: " + this);
- running = true;
- fire();
+ LOG.info("Starting: " + this);
+ running = true;
+ fire();
- // Start a background stats printer if INFO level logging is enabled
- if (STATS_LOG.isLoggable(Level.INFO) || STATS_LOG.isLoggable(Level.FINEST)) {
- if (STATS_LOG.isLoggable(Level.FINEST)) {
- LOG.info("On " + this + ", enabling periodic statistics output at INFO level every 30 seconds on category: " + STATS_LOG.getName());
- } else {
- LOG.info("On " + this + ", enabling periodic full memory dump at FINEST level every 30 seconds on category: " + STATS_LOG.getName());
- }
- statsTimer = executorService.scheduleAtFixedRate(this::printSessionStats, 3, 30, TimeUnit.SECONDS);
+ // Start a background stats printer if INFO level logging is enabled
+ if (STATS_LOG.isLoggable(Level.INFO) || STATS_LOG.isLoggable(Level.FINEST)) {
+ if (STATS_LOG.isLoggable(Level.FINEST)) {
+ LOG.info("On " + this + ", enabling periodic statistics output at INFO level every 30 seconds on category: " + STATS_LOG.getName());
+ } else {
+ LOG.info("On " + this + ", enabling periodic full memory dump at FINEST level every 30 seconds on category: " + STATS_LOG.getName());
}
+ statsTimer = executorService.scheduleAtFixedRate(this::printSessionStats, 3, 30, TimeUnit.SECONDS);
}
}
public void fire() {
// Submit a task that fires the engine for all deployments
- executorService.submit(() -> {
- synchronized (deployments) {
-
- if (!running) {
- return;
- }
+ executorService.submit(() -> withLock(getClass().getSimpleName(), () -> {
+ if (!running) {
+ return;
+ }
- // Set the current clock
- RulesClock clock = new RulesClock(timerService);
- facts.setClock(clock);
+ // Set the current clock
+ RulesClock clock = new RulesClock(timerService);
+ facts.setClock(clock);
- // Remove any expired temporary facts
- boolean factsExpired = facts.removeExpiredTemporaryFacts();
+ // Remove any expired temporary facts
+ boolean factsExpired = facts.removeExpiredTemporaryFacts();
- // 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")
+ // 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")
- for (RulesetDeployment deployment : deployments.values()) {
- try {
- RULES_LOG.fine("Firing rules @" + clock + " of: " + deployment);
+ for (RulesetDeployment deployment : deployments.values()) {
+ try {
+ RULES_LOG.fine("Firing rules @" + clock + " of: " + deployment);
- // 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);
- }
+ // 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);
+ }
- engine.fire(deployment.getRules(), facts);
+ engine.fire(deployment.getRules(), facts);
- } catch (Exception ex) {
- LOG.log(Level.SEVERE, "On " + RulesEngine.this + ", error firing rules of: " + deployment, ex);
+ } catch (Exception ex) {
+ LOG.log(Level.SEVERE, "On " + RulesEngine.this + ", error firing rules of: " + deployment, ex);
- deployment.setStatus(EXECUTION_ERROR);
- deployment.setError(ex);
+ deployment.setStatus(EXECUTION_ERROR);
+ deployment.setError(ex);
- // 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 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;
- }
+ // TODO We skip any other deployment when we hit the first error, good idea?
+ break;
}
+ }
- // 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;
- }
+ // 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() {
- synchronized (deployments) {
- if (!isRunning()) {
- return;
- }
- LOG.info("Stopping: " + this);
- if (eventsTimer != null) {
- eventsTimer.cancel(true);
- eventsTimer = null;
- }
- if (statsTimer != null) {
- statsTimer.cancel(true);
- statsTimer = null;
- }
- running = false;
+ if (!isRunning()) {
+ return;
+ }
+ LOG.info("Stopping: " + this);
+ if (eventsTimer != null) {
+ eventsTimer.cancel(true);
+ eventsTimer = null;
}
+ if (statsTimer != null) {
+ statsTimer.cancel(true);
+ statsTimer = null;
+ }
+ running = false;
}
public void updateFact(AssetState assetState, boolean fireImmediately) {
- synchronized (deployments) {
- facts.putAssetState(assetState);
- if (fireImmediately) {
- fire();
- }
+ facts.putAssetState(assetState);
+ if (fireImmediately) {
+ fire();
}
}
public void removeFact(AssetState assetState) {
- synchronized (deployments) {
- facts.removeAssetState(assetState);
- fire();
- }
+ facts.removeAssetState(assetState);
+ fire();
}
public void insertFact(String expires, AssetState assetState) {
- synchronized (deployments) {
- facts.insertAssetEvent(expires, assetState);
- fire();
- }
+ facts.insertAssetEvent(expires, assetState);
+ fire();
}
/* TODO
@@ -418,7 +390,7 @@ public class RulesEngine<T extends Ruleset> {
}
protected void printSessionStats() {
- synchronized (deployments) {
+ withLock(getClass().getSimpleName(), () -> {
Collection<AssetState> assetStateFacts = facts.getAssetStates();
Collection<TemporaryFact<AssetState>> assetEventFacts = facts.getAssetEvents();
Map<String, Object> namedFacts = facts.getNamedFacts();
@@ -434,7 +406,7 @@ public class RulesEngine<T extends Ruleset> {
if (STATS_LOG.isLoggable(Level.FINEST)) {
facts.logFacts(STATS_LOG);
}
- }
+ });
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index e311e83f4..ca5cf1309 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -51,6 +51,8 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.logging.Level.FINEST;
+import static org.openremote.container.concurrent.GlobalLock.withLock;
+import static org.openremote.container.concurrent.GlobalLock.withLockReturning;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForEntityType;
import static org.openremote.container.util.MapAccess.getString;
@@ -59,17 +61,26 @@ import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttributes;
/**
- * Responsible for creating {@link RulesEngine}s for the rulesets
- * and processing {@link AssetState} updates.
+ * Manages {@link RulesEngine}s for stored {@link Ruleset}s and processes asset attribute updates.
* <p>
- * Each message is processed in the following order:
+ * If an updated attribute {@link AssetAttribute#isRuleState}, this implementation of
+ * {@link AssetUpdateProcessor} converts the update message to an {@link AssetState} fact.
+ * This service keeps the facts and thus the state of rule facts are in sync with the asset state
+ * changes that occur. If an asset attribute value changes, the {@link AssetState} in the rules
+ * engines will be updated to reflect the change.
+ * <p>
+ * If an updated attribute {@link AssetAttribute#isRuleEvent}, another temporary {@link AssetState}
+ * fact is inserted in the rules engines in scope. This fact expires automatically if the lifetime
+ * set in {@link RulesService#RULE_EVENT_EXPIRES} is reached, or if the lifetime set in the
+ * attribute {@link AssetMeta#RULE_EVENT_EXPIRES} is reached.
+ * <p>
+ * Each asset attribute update is processed in the following order:
* <ol>
* <li>Global Rulesets</li>
* <li>Tenant Rulesets</li>
- * <li>Asset Rulesets (in hierarchical order from oldest ancestor down - ordering of
- * asset rulesets with same parent asset are not guaranteed also processing order of rulesets
- * with the same scope is not guaranteed)</li>
+ * <li>Asset Rulesets (in hierarchical order from oldest ancestor down)</li>
* </ol>
+ * Processing order of rulesets with the same scope or same parent is not guaranteed.
*/
public class RulesService extends RouteBuilder implements ContainerService, AssetUpdateProcessor {
@@ -182,20 +193,17 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
@Override
public void stop(Container container) throws Exception {
- synchronized (assetEngines) {
+ withLock(getClass().getSimpleName(), () -> {
assetEngines.forEach((assetId, rulesEngine) -> rulesEngine.stop());
assetEngines.clear();
- }
-
- synchronized (tenantEngines) {
tenantEngines.forEach((realm, rulesEngine) -> rulesEngine.stop());
tenantEngines.clear();
- }
- if (globalEngine != null) {
- globalEngine.stop();
- globalEngine = null;
- }
+ if (globalEngine != null) {
+ globalEngine.stop();
+ globalEngine = null;
+ }
+ });
}
@Override
@@ -225,280 +233,294 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
return false;
}
- protected synchronized void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {
- // Check if enabled status has changed
- boolean wasEnabled = Arrays.asList(activeTenantIds).contains(tenant.getId());
- boolean isEnabled = tenant.getEnabled() && cause != PersistenceEvent.Cause.DELETE;
- activeTenantIds = identityService.getIdentityProvider().getActiveTenantIds();
-
- if (wasEnabled == isEnabled) {
- // Nothing to do here
- return;
- }
+ protected void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {
+ withLock(getClass().getSimpleName(), () -> {
+ // Check if enabled status has changed
+ boolean wasEnabled = Arrays.asList(activeTenantIds).contains(tenant.getId());
+ boolean isEnabled = tenant.getEnabled() && cause != PersistenceEvent.Cause.DELETE;
+ activeTenantIds = identityService.getIdentityProvider().getActiveTenantIds();
- if (wasEnabled) {
- // Remove tenant rules engine for this tenant if it exists
- RulesEngine<TenantRuleset> tenantRulesEngine = tenantEngines.get(tenant.getId());
- if (tenantRulesEngine != null) {
- tenantRulesEngine.stop();
- tenantEngines.remove(tenant.getId());
+ if (wasEnabled == isEnabled) {
+ // Nothing to do here
+ return;
}
- // Remove any asset rules engines for assets in this realm
- assetEngines.values().stream()
- .filter(re -> re.getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false))
- .forEach(RulesEngine::stop);
- assetEngines.entrySet().removeIf(entry ->
- entry.getValue().getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false)
- );
+ if (wasEnabled) {
+ // Remove tenant rules engine for this tenant if it exists
+ RulesEngine<TenantRuleset> tenantRulesEngine = tenantEngines.get(tenant.getId());
+ if (tenantRulesEngine != null) {
+ tenantRulesEngine.stop();
+ tenantEngines.remove(tenant.getId());
+ }
+
+ // Remove any asset rules engines for assets in this realm
+ assetEngines.values().stream()
+ .filter(re -> re.getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false))
+ .forEach(RulesEngine::stop);
+ assetEngines.entrySet().removeIf(entry ->
+ entry.getValue().getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false)
+ );
- } else {
- // Create tenant rules engines for this tenant if it has any rulesets
- rulesetStorageService
- .findEnabledTenantRulesets(tenant.getId())
- .forEach(this::deployTenantRuleset);
+ } else {
+ // Create tenant rules engines for this tenant if it has any rulesets
+ rulesetStorageService
+ .findEnabledTenantRulesets(tenant.getId())
+ .forEach(this::deployTenantRuleset);
- // Create any asset rules engines for assets in this realm that have rulesets
- deployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets(tenant.getId()));
- }
+ // Create any asset rules engines for assets in this realm that have rulesets
+ deployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets(tenant.getId()));
+ }
+ });
}
- protected synchronized void processAssetChange(ServerAsset asset, PersistenceEvent persistenceEvent) {
+ protected void processAssetChange(ServerAsset asset, PersistenceEvent persistenceEvent) {
+ withLock(getClass().getSimpleName(), () -> {
+
+ // We must load the asset from database (only when required), as the
+ // persistence event might not contain a completely loaded asset
+ BiFunction<Asset, AssetAttribute, AssetState> buildAssetState = (loadedAsset, attribute) ->
+ new AssetState(loadedAsset, attribute.deepCopy(), Source.INTERNAL);
- // We must load the asset from database (only when required), as the
- // persistence event might not contain a completely loaded asset
- BiFunction<Asset, AssetAttribute, AssetState> buildAssetState = (loadedAsset, attribute) ->
- new AssetState(loadedAsset, attribute.deepCopy(), Source.INTERNAL);
+ switch (persistenceEvent.getCause()) {
+ case INSERT:
- switch (persistenceEvent.getCause()) {
- case INSERT:
+ // New asset has been created so get attributes that have RULE_STATE meta
+ List<AssetAttribute> ruleStateAttributes =
+ asset.getAttributesStream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());
+
+ // Build an update with a fully loaded asset
+ ruleStateAttributes.forEach(attribute -> {
+ ServerAsset loadedAsset = assetStorageService.find(asset.getId(), true);
+ // If the asset is now gone it was deleted immediately after being inserted, nothing more to do
+ if (loadedAsset == null)
+ return;
+
+ AssetState assetState = buildAssetState.apply(loadedAsset, attribute);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + assetState);
+ updateAssetState(assetState, true, true);
+ });
+ break;
- // New asset has been created so get attributes that have RULE_STATE meta
- List<AssetAttribute> ruleStateAttributes =
- asset.getAttributesStream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());
+ case UPDATE:
- // Build an update with a fully loaded asset
- ruleStateAttributes.forEach(attribute -> {
- ServerAsset loadedAsset = assetStorageService.find(asset.getId(), true);
- // If the asset is now gone it was deleted immediately after being inserted, nothing more to do
+ int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
+ if (attributesIndex < 0) {
+ return;
+ }
+
+ // Fully load the asset
+ final Asset loadedAsset = assetStorageService.find(asset.getId(), true);
+ // If the asset is now gone it was deleted immediately after being updated, nothing more to do
if (loadedAsset == null)
return;
- AssetState assetState = buildAssetState.apply(loadedAsset, attribute);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + assetState);
- updateAssetState(assetState, true, true);
- });
- break;
+ // Attributes have possibly changed so need to compare old and new attributes
+ // to determine which facts to retract and which to insert
+ List<AssetAttribute> oldRuleStateAttributes =
+ attributesFromJson(
+ (ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],
+ asset.getId()
+ ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
+
+ List<AssetAttribute> newRuleStateAttributes =
+ attributesFromJson(
+ (ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],
+ asset.getId()
+ ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
+
+ // Retract facts for attributes that are obsolete
+ getAddedOrModifiedAttributes(newRuleStateAttributes, oldRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME))
+ .forEach(obsoleteFactAttribute -> {
+ AssetState update = buildAssetState.apply(loadedAsset, obsoleteFactAttribute);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting: " + update);
+ retractAssetState(update);
+ });
+
+ // Insert facts for attributes that are new
+ getAddedOrModifiedAttributes(oldRuleStateAttributes, newRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME))
+ .forEach(newFactAttribute -> {
+ AssetState assetState = buildAssetState.apply(loadedAsset, newFactAttribute);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), updating: " + assetState);
+ updateAssetState(assetState, true, true);
+ });
+ break;
+
+ case DELETE:
+ // Retract any facts that were associated with this asset
+ asset.getAttributesStream()
+ .filter(AssetAttribute::isRuleState)
+ .forEach(attribute -> {
+ // We can't load the asset again (it was deleted), so don't use buildAssetState() and
+ // hope that the path of the event asset has been loaded before deletion, although it is
+ // "unlikely" anybody will access it during retraction...
+ AssetState assetState = new AssetState(asset, attribute, Source.INTERNAL);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + assetState);
+ retractAssetState(assetState);
+ });
+ break;
+ }
- case UPDATE:
+ if (persistenceEvent.getCause() != PersistenceEvent.Cause.INSERT) {
int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
if (attributesIndex < 0) {
return;
}
- // Fully load the asset
- final Asset loadedAsset = assetStorageService.find(asset.getId(), true);
- // If the asset is now gone it was deleted immediately after being updated, nothing more to do
- if (loadedAsset == null)
- return;
-
- // Attributes have possibly changed so need to compare old and new attributes
- // to determine which facts to retract and which to insert
- List<AssetAttribute> oldRuleStateAttributes =
+ // Get old template filter attributes and new ones
+ // If new collection doesn't contain them, then they are deleted and need to be processed too
+ List<AssetAttribute> oldTemplateFilterAttributes = persistenceEvent.getPreviousState() != null ? //can be null when insert
attributesFromJson(
(ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],
asset.getId()
- ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
+ ).filter(attribute -> attribute.getTypeOrThrow() == AttributeType.RULES_TEMPLATE_FILTER)
+ .collect(Collectors.toList()) : new ArrayList<>();
- List<AssetAttribute> newRuleStateAttributes =
+ List<AssetAttribute> newTemplateFilterAttributes = persistenceEvent.getCurrentState() != null ? // can be null when delete
attributesFromJson(
(ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],
asset.getId()
- ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());
-
- // Retract facts for attributes that are obsolete
- getAddedOrModifiedAttributes(newRuleStateAttributes, oldRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME))
- .forEach(obsoleteFactAttribute -> {
- AssetState update = buildAssetState.apply(loadedAsset, obsoleteFactAttribute);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting: " + update);
- retractAssetState(update);
- });
+ ).filter(attribute -> attribute.getTypeOrThrow() == AttributeType.RULES_TEMPLATE_FILTER)
+ .collect(Collectors.toList()) : new ArrayList<>();
- // Insert facts for attributes that are new
- getAddedOrModifiedAttributes(oldRuleStateAttributes, newRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME))
- .forEach(newFactAttribute -> {
- AssetState assetState = buildAssetState.apply(loadedAsset, newFactAttribute);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), updating: " + assetState);
- updateAssetState(assetState, true, true);
- });
- break;
-
- case DELETE:
- // Retract any facts that were associated with this asset
- asset.getAttributesStream()
- .filter(AssetAttribute::isRuleState)
- .forEach(attribute -> {
- // We can't load the asset again (it was deleted), so don't use buildAssetState() and
- // hope that the path of the event asset has been loaded before deletion, although it is
- // "unlikely" anybody will access it during retraction...
- AssetState assetState = new AssetState(asset, attribute, Source.INTERNAL);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + assetState);
- retractAssetState(assetState);
- });
- break;
- }
+ if (!oldTemplateFilterAttributes.isEmpty() || !newTemplateFilterAttributes.isEmpty()) {
+ rulesetStorageService.findTemplatedAssetRulesets(asset.getRealmId(), asset.getId())
+ .forEach(assetRuleset -> processRulesetChange(assetRuleset, persistenceEvent.getCause()));
- if (persistenceEvent.getCause() != PersistenceEvent.Cause.INSERT) {
+ rulesetStorageService.findTemplatedTenantRulesets(asset.getRealmId(), asset.getId())
+ .forEach(tenantRuleset -> processRulesetChange(tenantRuleset, persistenceEvent.getCause()));
- int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
- if (attributesIndex < 0) {
- return;
- }
-
- // Get old template filter attributes and new ones
- // If new collection doesn't contain them, then they are deleted and need to be processed too
- List<AssetAttribute> oldTemplateFilterAttributes = persistenceEvent.getPreviousState() != null ? //can be null when insert
- attributesFromJson(
- (ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],
- asset.getId()
- ).filter(attribute -> attribute.getTypeOrThrow() == AttributeType.RULES_TEMPLATE_FILTER)
- .collect(Collectors.toList()) : new ArrayList<>();
-
- List<AssetAttribute> newTemplateFilterAttributes = persistenceEvent.getCurrentState() != null ? // can be null when delete
- attributesFromJson(
- (ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],
- asset.getId()
- ).filter(attribute -> attribute.getTypeOrThrow() == AttributeType.RULES_TEMPLATE_FILTER)
- .collect(Collectors.toList()) : new ArrayList<>();
-
- if (!oldTemplateFilterAttributes.isEmpty() || !newTemplateFilterAttributes.isEmpty()) {
- rulesetStorageService.findTemplatedAssetRulesets(asset.getRealmId(), asset.getId())
- .forEach(assetRuleset -> processRulesetChange(assetRuleset, persistenceEvent.getCause()));
-
- rulesetStorageService.findTemplatedTenantRulesets(asset.getRealmId(), asset.getId())
- .forEach(tenantRuleset -> processRulesetChange(tenantRuleset, persistenceEvent.getCause()));
-
- rulesetStorageService.findTemplatedGlobalRulesets(asset.getId())
- .forEach(globalRuleset -> processRulesetChange(globalRuleset, persistenceEvent.getCause()));
+ rulesetStorageService.findTemplatedGlobalRulesets(asset.getId())
+ .forEach(globalRuleset -> processRulesetChange(globalRuleset, persistenceEvent.getCause()));
+ }
}
- }
+ });
}
- protected synchronized void processRulesetChange(Ruleset ruleset, PersistenceEvent.Cause cause) {
- if (cause == PersistenceEvent.Cause.DELETE || !ruleset.isEnabled()) {
- if (ruleset instanceof GlobalRuleset) {
- undeployGlobalRuleset((GlobalRuleset) ruleset);
- } else if (ruleset instanceof TenantRuleset) {
- undeployTenantRuleset((TenantRuleset) ruleset);
- } else if (ruleset instanceof AssetRuleset) {
- undeployAssetRuleset((AssetRuleset) ruleset);
- }
- } else {
- if (ruleset instanceof GlobalRuleset) {
-
- RulesEngine newEngine = deployGlobalRuleset((GlobalRuleset) ruleset);
- if (newEngine != null) {
- // Push all existing facts into the engine, this is an initial import of state so fire delayed
- assetStates.forEach(assetState -> newEngine.updateFact(assetState, false));
- newEngine.fire();
+ protected void processRulesetChange(Ruleset ruleset, PersistenceEvent.Cause cause) {
+ withLock(getClass().getSimpleName(), () -> {
+ if (cause == PersistenceEvent.Cause.DELETE || !ruleset.isEnabled()) {
+ if (ruleset instanceof GlobalRuleset) {
+ undeployGlobalRuleset((GlobalRuleset) ruleset);
+ } else if (ruleset instanceof TenantRuleset) {
+ undeployTenantRuleset((TenantRuleset) ruleset);
+ } else if (ruleset instanceof AssetRuleset) {
+ undeployAssetRuleset((AssetRuleset) ruleset);
}
+ } else {
+ if (ruleset instanceof GlobalRuleset) {
+
+ RulesEngine newEngine = deployGlobalRuleset((GlobalRuleset) ruleset);
+ if (newEngine != null) {
+ // Push all existing facts into the engine, this is an initial import of state so fire delayed
+ assetStates.forEach(assetState -> newEngine.updateFact(assetState, false));
+ newEngine.fire();
+ }
- } else if (ruleset instanceof TenantRuleset) {
-
- RulesEngine newEngine = deployTenantRuleset((TenantRuleset) ruleset);
- if (newEngine != null) {
- // Push all existing facts into the engine, this is an initial import of state so fire delayed
- assetStates.forEach(assetState -> {
- if (assetState.getRealmId().equals(((TenantRuleset) ruleset).getRealmId())) {
- newEngine.updateFact(assetState, false);
- }
- });
- newEngine.fire();
- }
+ } else if (ruleset instanceof TenantRuleset) {
+
+ RulesEngine newEngine = deployTenantRuleset((TenantRuleset) ruleset);
+ if (newEngine != null) {
+ // Push all existing facts into the engine, this is an initial import of state so fire delayed
+ assetStates.forEach(assetState -> {
+ if (assetState.getRealmId().equals(((TenantRuleset) ruleset).getRealmId())) {
+ newEngine.updateFact(assetState, false);
+ }
+ });
+ newEngine.fire();
+ }
- } else if (ruleset instanceof AssetRuleset) {
-
- // Must reload from the database, the ruleset might not be completely hydrated on INSERT or UPDATE
- AssetRuleset assetRuleset = rulesetStorageService.findEnabledAssetRuleset(ruleset.getId());
- RulesEngine newEngine = deployAssetRuleset(assetRuleset);
- if (newEngine != null) {
- // Push all existing facts for this asset (and it's children into the engine), this is an
- // initial import of state so fire delayed
- getAssetStatesInScope(((AssetRuleset) ruleset).getAssetId())
- .forEach(assetState -> newEngine.updateFact(assetState, false));
- newEngine.fire();
+ } else if (ruleset instanceof AssetRuleset) {
+
+ // Must reload from the database, the ruleset might not be completely hydrated on INSERT or UPDATE
+ AssetRuleset assetRuleset = rulesetStorageService.findEnabledAssetRuleset(ruleset.getId());
+ RulesEngine newEngine = deployAssetRuleset(assetRuleset);
+ if (newEngine != null) {
+ // Push all existing facts for this asset (and it's children into the engine), this is an
+ // initial import of state so fire delayed
+ getAssetStatesInScope(((AssetRuleset) ruleset).getAssetId())
+ .forEach(assetState -> newEngine.updateFact(assetState, false));
+ newEngine.fire();
+ }
}
}
- }
+ });
}
/**
* 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 RulesEngine<GlobalRuleset> deployGlobalRuleset(GlobalRuleset ruleset) {
- boolean created = globalEngine == null;
-
- // Global rules have access to everything in the system
- if (globalEngine == null) {
- globalEngine = new RulesEngine<>(
- timerService,
- identityService,
- executorService,
- assetStorageService,
- assetProcessingService,
- notificationService,
- new RulesEngineId<>()
- );
- }
-
- globalEngine.addRuleset(ruleset);
- return created ? globalEngine : null;
- }
-
- protected synchronized void undeployGlobalRuleset(GlobalRuleset ruleset) {
- if (globalEngine == null) {
- return;
- }
-
- if (globalEngine.removeRuleset(ruleset)) {
- globalEngine = null;
- }
- }
+ protected RulesEngine<GlobalRuleset> deployGlobalRuleset(GlobalRuleset ruleset) {
+ return withLockReturning(getClass().getSimpleName(), () -> {
+ boolean created = globalEngine == null;
- protected synchronized RulesEngine<TenantRuleset> deployTenantRuleset(TenantRuleset ruleset) {
- final boolean[] created = {false};
-
- // Look for existing rules engines for this tenant
- RulesEngine<TenantRuleset> tenentRulesEngine = tenantEngines
- .computeIfAbsent(ruleset.getRealmId(), (realmId) -> {
- created[0] = true;
- return new RulesEngine<>(
+ // Global rules have access to everything in the system
+ if (globalEngine == null) {
+ globalEngine = new RulesEngine<>(
timerService,
identityService,
executorService,
assetStorageService,
assetProcessingService,
notificationService,
- new RulesEngineId<>(realmId)
+ new RulesEngineId<>()
);
- });
+ }
+
+ globalEngine.addRuleset(ruleset);
+ return created ? globalEngine : null;
+ });
+ }
- tenentRulesEngine.addRuleset(ruleset);
+ protected void undeployGlobalRuleset(GlobalRuleset ruleset) {
+ withLock(getClass().getSimpleName(), () -> {
+ if (globalEngine == null) {
+ return;
+ }
- return created[0] ? tenentRulesEngine : null;
+ if (globalEngine.removeRuleset(ruleset)) {
+ globalEngine = null;
+ }
+ });
}
- protected synchronized void undeployTenantRuleset(TenantRuleset ruleset) {
- RulesEngine<TenantRuleset> rulesEngine = tenantEngines.get(ruleset.getRealmId());
- if (rulesEngine == null) {
- return;
- }
+ protected RulesEngine<TenantRuleset> deployTenantRuleset(TenantRuleset ruleset) {
+ return withLockReturning(getClass().getSimpleName(), () -> {
+ final boolean[] created = {false};
+
+ // Look for existing rules engines for this tenant
+ RulesEngine<TenantRuleset> tenentRulesEngine = tenantEngines
+ .computeIfAbsent(ruleset.getRealmId(), (realmId) -> {
+ created[0] = true;
+ return new RulesEngine<>(
+ timerService,
+ identityService,
+ executorService,
+ assetStorageService,
+ assetProcessingService,
+ notificationService,
+ new RulesEngineId<>(realmId)
+ );
+ });
- if (rulesEngine.removeRuleset(ruleset)) {
- tenantEngines.remove(ruleset.getRealmId());
- }
+ tenentRulesEngine.addRuleset(ruleset);
+
+ return created[0] ? tenentRulesEngine : null;
+ });
+ }
+
+ protected void undeployTenantRuleset(TenantRuleset ruleset) {
+ withLock(getClass().getSimpleName(), () -> {
+ RulesEngine<TenantRuleset> rulesEngine = tenantEngines.get(ruleset.getRealmId());
+ if (rulesEngine == null) {
+ return;
+ }
+
+ if (rulesEngine.removeRuleset(ruleset)) {
+ tenantEngines.remove(ruleset.getRealmId());
+ }
+ });
}
protected void deployAssetRulesets(List<AssetRuleset> rulesets) {
@@ -529,86 +551,94 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
});
}
- protected synchronized RulesEngine<AssetRuleset> deployAssetRuleset(AssetRuleset ruleset) {
- final boolean[] created = {false};
-
- // Look for existing rules engine for this asset
- RulesEngine<AssetRuleset> assetRulesEngine = assetEngines
- .computeIfAbsent(ruleset.getAssetId(), (assetId) -> {
- created[0] = true;
- return new RulesEngine<>(
- timerService,
- identityService,
- executorService,
- assetStorageService,
- assetProcessingService,
- notificationService,
- new RulesEngineId<>(ruleset.getRealmId(), assetId)
- );
- });
+ protected RulesEngine<AssetRuleset> deployAssetRuleset(AssetRuleset ruleset) {
+ return withLockReturning(getClass().getSimpleName(), () -> {
+ final boolean[] created = {false};
+
+ // Look for existing rules engine for this asset
+ RulesEngine<AssetRuleset> assetRulesEngine = assetEngines
+ .computeIfAbsent(ruleset.getAssetId(), (assetId) -> {
+ created[0] = true;
+ return new RulesEngine<>(
+ timerService,
+ identityService,
+ executorService,
+ assetStorageService,
+ assetProcessingService,
+ notificationService,
+ new RulesEngineId<>(ruleset.getRealmId(), assetId)
+ );
+ });
- assetRulesEngine.addRuleset(ruleset);
- return created[0] ? assetRulesEngine : null;
+ assetRulesEngine.addRuleset(ruleset);
+ return created[0] ? assetRulesEngine : null;
+ });
}
- protected synchronized void undeployAssetRuleset(AssetRuleset ruleset) {
- RulesEngine<AssetRuleset> assetRulesEngine = assetEngines.get(ruleset.getAssetId());
- if (assetRulesEngine == null) {
- return;
- }
+ protected void undeployAssetRuleset(AssetRuleset ruleset) {
+ withLock(getClass().getSimpleName(), () -> {
+ RulesEngine<AssetRuleset> assetRulesEngine = assetEngines.get(ruleset.getAssetId());
+ if (assetRulesEngine == null) {
+ return;
+ }
- if (assetRulesEngine.removeRuleset(ruleset)) {
- assetEngines.remove(ruleset.getAssetId());
- }
+ if (assetRulesEngine.removeRuleset(ruleset)) {
+ assetEngines.remove(ruleset.getAssetId());
+ }
+ });
}
- protected synchronized void insertAssetEvent(AssetState assetState, String expires) {
- // Get the chain of rule engines that we need to pass through
- List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPath());
+ protected void insertAssetEvent(AssetState assetState, String expires) {
+ withLock(getClass().getSimpleName(), () -> {
+ // Get the chain of rule engines that we need to pass through
+ List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPath());
- // Check that all engines in the scope are available
- if (rulesEngines.stream().anyMatch(RulesEngine::isError)) {
- LOG.severe("At least one rules engine is in an error state, skipping: " + assetState);
- if (LOG.isLoggable(FINEST)) {
- for (RulesEngine rulesEngine : rulesEngines) {
- if (rulesEngine.isError()) {
- LOG.log(FINEST, "Rules engine error state: " + rulesEngine, rulesEngine.getError());
+ // Check that all engines in the scope are available
+ if (rulesEngines.stream().anyMatch(RulesEngine::isError)) {
+ LOG.severe("At least one rules engine is in an error state, skipping: " + assetState);
+ if (LOG.isLoggable(FINEST)) {
+ for (RulesEngine rulesEngine : rulesEngines) {
+ if (rulesEngine.isError()) {
+ LOG.log(FINEST, "Rules engine error state: " + rulesEngine, rulesEngine.getError());
+ }
}
}
+ return;
}
- return;
- }
- // Pass through each engine
- for (RulesEngine rulesEngine : rulesEngines) {
- rulesEngine.insertFact(expires, assetState);
- }
+ // Pass through each engine
+ for (RulesEngine rulesEngine : rulesEngines) {
+ rulesEngine.insertFact(expires, assetState);
+ }
+ });
}
- protected synchronized void updateAssetState(AssetState assetState, boolean skipStatusCheck, boolean fireImmediately) {
- // TODO: implement rules processing error state handling
+ protected void updateAssetState(AssetState assetState, boolean skipStatusCheck, boolean fireImmediately) {
+ withLock(getClass().getSimpleName(), () -> {
+ // TODO: implement rules processing error state handling
- // Get the chain of rule engines that we need to pass through
- List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPath());
+ // Get the chain of rule engines that we need to pass through
+ List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPath());
- if (!skipStatusCheck) {
- // Check that all engines in the scope are available
- // TODO This is not very useful without locking the engines until we are done with the update
- for (RulesEngine rulesEngine : rulesEngines) {
- if (rulesEngine.isError()) {
- throw rulesEngine.getError();
+ if (!skipStatusCheck) {
+ // Check that all engines in the scope are available
+ // TODO This is not very useful without locking the engines until we are done with the update
+ for (RulesEngine rulesEngine : rulesEngines) {
+ if (rulesEngine.isError()) {
+ throw rulesEngine.getError();
+ }
}
}
- }
- // Remove asset state with same attribute ref as new state, add new state
- assetStates.remove(assetState);
- assetStates.add(assetState);
+ // Remove asset state with same attribute ref as new state, add new state
+ assetStates.remove(assetState);
+ assetStates.add(assetState);
- // Pass through each rules engine
- for (RulesEngine rulesEngine : rulesEngines) {
- rulesEngine.updateFact(assetState, fireImmediately);
- }
+ // Pass through each rules engine
+ for (RulesEngine rulesEngine : rulesEngines) {
+ rulesEngine.updateFact(assetState, fireImmediately);
+ }
+ });
}
protected void retractAssetState(AssetState assetState) {
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20180119_01__Ruleset_Lang.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20180119_01__Ruleset_Lang.sql
index edef007bb..a817318ec 100644
--- a/manager/src/main/resources/org/openremote/manager/setup/database/V20180119_01__Ruleset_Lang.sql
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20180119_01__Ruleset_Lang.sql
@@ -1,5 +1,5 @@
alter table ASSET_RULESET
- add column RULES_LANG varchar(255) not null default 'ECMASCRIPT_5_1';
+ add column RULES_LANG varchar(255) not null default 'JAVASCRIPT';
alter table GLOBAL_RULESET
add column RULES_LANG varchar(255) not null default 'ECMASCRIPT_5_1';
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20180214_01__Ruleset_Default_Lang.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20180214_01__Ruleset_Default_Lang.sql
new file mode 100644
index 000000000..82317e415
--- /dev/null
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20180214_01__Ruleset_Default_Lang.sql
@@ -0,0 +1,11 @@
+-- alter table ASSET_DATAPOINT
+-- alter column VALUE DROP NOT NULL;
+
+alter table ASSET_RULESET
+ alter column RULES_LANG set default 'GROOVY';
+
+alter table GLOBAL_RULESET
+ alter column RULES_LANG set default 'GROOVY';
+
+alter table TENANT_RULESET
+ alter column RULES_LANG set default 'GROOVY';
diff --git a/model/src/main/java/org/openremote/model/asset/agent/AgentStatusEvent.java b/model/src/main/java/org/openremote/model/asset/agent/AgentStatusEvent.java
index 6d28640ad..c593605f9 100644
--- a/model/src/main/java/org/openremote/model/asset/agent/AgentStatusEvent.java
+++ b/model/src/main/java/org/openremote/model/asset/agent/AgentStatusEvent.java
@@ -52,7 +52,7 @@ public class AgentStatusEvent extends TenantScopedEvent {
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- "realmId =" + realmId +
+ "realmId=" + realmId +
", protocolConfiguration=" + protocolConfiguration +
", connectionStatus=" + connectionStatus +
'}';
diff --git a/test/build.gradle b/test/build.gradle
index 2d2dc65cc..5ca27e399 100644
--- a/test/build.gradle
+++ b/test/build.gradle
@@ -39,4 +39,9 @@ dependencies {
test {
workingDir = findProject(":openremote") != null ? resolveProject("").projectDir : rootProject.projectDir
+ testLogging {
+ outputs.upToDateWhen {false}
+ // Enable this to show STDOUT/STDERR on console when running tests
+ // showStandardStreams = true
+ }
}
\ No newline at end of file
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
index b5765fbf4..d44f43810 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
@@ -38,7 +38,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
when: "a simulated sensor receives a new value"
advancePseudoClock(10, SECONDS, container)
def datapoint1ExpectedTimestamp = getClockTimeOf(container)
- simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3))
+ simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3d))
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
@@ -48,7 +48,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
when: "a simulated sensor receives a new value"
advancePseudoClock(10, SECONDS, container)
def datapoint2ExpectedTimestamp = getClockTimeOf(container)
- simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(14.4))
+ simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(14.4d))
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
@@ -58,18 +58,30 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
when: "a simulated sensor receives a new value"
advancePseudoClock(10, SECONDS, container)
def datapoint3ExpectedTimestamp = getClockTimeOf(container)
- simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(15.5))
+ simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(15.5d))
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValueAsNumber() }.orElse(null) == 15.5d
}
+ when: "a simulated sensor receives a new value"
+ advancePseudoClock(10, SECONDS, container)
+ simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", null) // No value!
+ then: "the attribute should be updated"
+ conditions.eventually {
+ def thing = assetStorageService.find(managerDemoSetup.thingId, true)
+ assert !thing.getAttribute("light1PowerConsumption").flatMap { it.getValue() }.isPresent()
+ }
+
expect: "the datapoints to be stored"
conditions.eventually {
def datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))
assert datapoints.size() > 3
+ // Note that the "No value" sensor update should not have created a datapoint, the first
+ // datapoint is the last sensor update with an actual value
+
assert Values.getNumber(datapoints.get(0).value).orElse(null) == 15.5d
assert datapoints.get(0).timestamp == datapoint3ExpectedTimestamp
diff --git a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
index 307587ca2..c0f43dbd9 100644
--- a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
@@ -108,7 +108,7 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
assert collectedSharedEvents[1] instanceof AgentStatusEvent
assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId
assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName
- assert (collectedSharedEvents[1] as AgentStatusEvent).connectionStatus == ConnectionStatus.CONNECTING
+ assert (collectedSharedEvents[1] as AgentStatusEvent).connectionStatus == ConnectionStatus.WAITING
assert collectedSharedEvents[2] instanceof AgentStatusEvent
assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId
assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName
diff --git a/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy
index de74d51b2..8b8022876 100644
--- a/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy
@@ -19,7 +19,7 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaine
def "Rule condition invalid return"() {
given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 5, delay: 1)
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
@@ -56,7 +56,7 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaine
def "Rule condition throws exception"() {
given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 5, delay: 1)
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
@@ -93,7 +93,7 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaine
def "Rule action throws exception"() {
given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 5, delay: 1)
+ def conditions = new PollingConditions(timeout: 10, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
index 90b359ecc..0680f22a4 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
@@ -10,11 +10,11 @@ import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.asset.ServerAsset
-import org.openremote.model.asset.agent.AgentResource
import org.openremote.model.asset.AssetAttribute
import org.openremote.model.asset.AssetMeta
import org.openremote.model.asset.AssetType
import org.openremote.model.asset.agent.AgentLink
+import org.openremote.model.asset.agent.AgentResource
import org.openremote.model.attribute.AttributeRef
import org.openremote.model.attribute.AttributeType
import org.openremote.model.attribute.MetaItem
@@ -218,5 +218,8 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
def memoTextAttribute = asset.getAttributesList().find {VelbusConfiguration.getVelbusDevicePropertyLink(it) == "MEMO_TEXT"}
assert memoTextAttribute != null
assert VelbusConfiguration.getVelbusDeviceAddress(memoTextAttribute) == 24
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
}
}