Skip to content

armgit / core

Public Imported from GitHub
0

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

AttributeEvent processing updates

Rich Turner3028e740d26a
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 22b850d5c..beef8ce1f 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
@@ -33,14 +33,13 @@ import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.util.Triplet;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
public abstract class AbstractProtocol implements Protocol {
@@ -173,6 +172,24 @@ public abstract class AbstractProtocol implements Protocol {
}
}
+ @Override
+ public List<AssetAttribute> getLinkedProtocolConfigurations() {
+ synchronized (linkedProtocolConfigurations) {
+ return linkedProtocolConfigurations
+ .values()
+ .stream()
+ .map(triplet -> triplet.getValue1())
+ .collect(Collectors.toList());
+ }
+ }
+
+ @Override
+ public List<AssetAttribute> getLinkedAttributes() {
+ synchronized (linkedAttributes) {
+ return new ArrayList<>(linkedAttributes.values());
+ }
+ }
+
/**
* Send an arbitrary {@link AttributeState} through the processing chain
* using the current system time as the timestamp. Use {@link #updateLinkedAttribute}
@@ -180,7 +197,7 @@ public abstract class AbstractProtocol implements Protocol {
* different messaging queue.
*/
protected void sendAttributeEvent(AttributeState state) {
- assetService.sendAttributeEvent(new AttributeEvent(state, timerService.getCurrentTimeMillis()));
+ assetService.sendAttributeEvent(this, new AttributeEvent(state, timerService.getCurrentTimeMillis()));
}
/**
@@ -189,7 +206,7 @@ public abstract class AbstractProtocol implements Protocol {
* additional verification and uses a different messaging queue.
*/
protected void sendAttributeEvent(AttributeEvent event) {
- assetService.sendAttributeEvent(event);
+ assetService.sendAttributeEvent(this, event);
}
/**
@@ -198,7 +215,11 @@ public abstract class AbstractProtocol implements Protocol {
protected void updateLinkedAttribute(AttributeState state, long timestamp) {
AttributeEvent attributeEvent = new AttributeEvent(state, timestamp);
LOG.fine("Sending on sensor queue: " + attributeEvent);
- producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, attributeEvent, Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, getProtocolName());
+ producerTemplate.sendBodyAndHeader(
+ SENSOR_QUEUE,
+ attributeEvent,
+ SharedEvent.HEADER_SENDER,
+ this);
}
/**
diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
index 5adef203b..ecee566e6 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
@@ -28,9 +28,11 @@ import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.value.ValueType;
import java.util.Collection;
+import java.util.List;
import java.util.function.Consumer;
/**
@@ -65,7 +67,7 @@ import java.util.function.Consumer;
* If the actual state of the device (or service) changes, the linked protocol writes the new
* state into the attribute value and notifies the context broker of the change. A protocol updates
* a linked attributes' value by sending an {@link AttributeEvent} messages on the
- * {@link #SENSOR_QUEUE}, including the source protocol name in header {@link #SENSOR_QUEUE_SOURCE_PROTOCOL}.
+ * {@link #SENSOR_QUEUE}, including the source protocol in header {@link SharedEvent#HEADER_SENDER}.
* <p>
* If the user writes a new value into the linked attribute, the protocol translates this value
* change into a device (or service) action. Write operations on attributes linked to a protocol
@@ -169,7 +171,6 @@ public interface Protocol extends ContainerService {
}
String ACTUATOR_TOPIC_TARGET_PROTOCOL = "Protocol";
- String SENSOR_QUEUE_SOURCE_PROTOCOL = "Protocol";
// TODO: Some of these options should be configurable depending on expected load etc.
@@ -181,6 +182,10 @@ public interface Protocol extends ContainerService {
String getProtocolName();
+ List<AssetAttribute> getLinkedProtocolConfigurations();
+
+ List<AssetAttribute> getLinkedAttributes();
+
/**
* Links attributes to their protocolConfiguration; the protocolConfiguration would have
* been linked before this call. If an attribute is not valid for this protocol or the protocol
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
index 37d4b4f19..620b79516 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
@@ -37,6 +37,6 @@ public interface ProtocolAssetService extends ContainerService {
/**
* Protocols can send arbitrary attribute change events for regular processing.
*/
- void sendAttributeEvent(AttributeEvent attributeEvent);
+ void sendAttributeEvent(Protocol sender, AttributeEvent attributeEvent);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
index 90e68f0cd..adcff235d 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
@@ -37,6 +37,7 @@ import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.util.Pair;
import org.openremote.model.value.ObjectValue;
@@ -53,6 +54,7 @@ import static org.openremote.agent.protocol.Protocol.DeploymentStatus.*;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForAssetType;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
+import static org.openremote.manager.server.asset.AssetProcessingService.ASSET_QUEUE;
import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
import static org.openremote.model.asset.AssetType.AGENT;
import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
@@ -176,8 +178,24 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
}
@Override
- public void sendAttributeEvent(AttributeEvent attributeEvent) {
- assetProcessingService.sendAttributeEvent(attributeEvent, false);
+ public void sendAttributeEvent(Protocol sender, AttributeEvent attributeEvent) {
+ // Don't allow updating linked attributes with this mechanism as it could cause
+ // an infinite loop
+ boolean isForLinkedAttribute = sender
+ .getLinkedAttributes()
+ .stream()
+ .anyMatch(attribute -> attribute.getReferenceOrThrow()
+ .equals(attributeEvent.getAttributeRef())
+ );
+
+ if (isForLinkedAttribute) {
+ LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that");
+ return;
+ }
+
+ messageBrokerService
+ .getProducerTemplate()
+ .sendBodyAndHeader(ASSET_QUEUE, attributeEvent, SharedEvent.HEADER_SENDER, sender);
}
/**
@@ -527,11 +545,11 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
*/
@Override
public void accept(AssetState assetState) {
- if (assetState.isSouthbound()) {
- LOG.fine("Handling south-bound update: " + assetState);
- } else {
- LOG.fine("Ignoring non-client update: " + assetState);
+ if (assetState.isSensorUpdate()) {
+ LOG.fine("Ignoring sensor update: " + assetState);
return;
+ } else {
+ LOG.fine("Handling update: " + assetState);
}
AgentLink.getAgentLink(assetState.getAttribute())
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
index d8ea43a3a..3c2625a7f 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
@@ -20,23 +20,28 @@
package org.openremote.manager.server.asset;
import org.apache.camel.builder.RouteBuilder;
+import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.agent.protocol.Protocol;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.manager.server.agent.AgentService;
import org.openremote.manager.server.datapoint.AssetDatapointService;
import org.openremote.manager.server.event.EventService;
+import org.openremote.manager.server.rules.RulesEngine;
import org.openremote.manager.server.rules.RulesService;
import org.openremote.manager.server.security.ManagerIdentityService;
+import org.openremote.manager.shared.asset.AssetProcessingException;
import org.openremote.manager.shared.security.ClientRole;
+import org.openremote.manager.shared.security.Tenant;
+import org.openremote.manager.shared.security.User;
import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.value.Values;
import java.util.ArrayList;
@@ -49,7 +54,6 @@ import java.util.logging.Logger;
import static org.openremote.agent.protocol.Protocol.SENSOR_QUEUE;
import static org.openremote.manager.server.event.EventService.INCOMING_EVENT_TOPIC;
-import static org.openremote.manager.server.event.EventService.getWebsocketAuth;
import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
/**
@@ -57,12 +61,22 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
* <p>
* {@link AttributeEvent}s can come from various sources:
* <ul>
- * <li>Protocol ({@link org.openremote.agent.protocol.AbstractProtocol#updateLinkedAttribute})</li>
- * <li>User/Client initiated ({@link #updateAttributeValue})</li>
- * <li>Rules ({@link org.openremote.model.rules.Assets#dispatch})</li>
+ * <li>Protocol sensor updates ({@link AbstractProtocol#updateLinkedAttribute})</li>
+ * <li>Protocol arbitrary updates ({@link AbstractProtocol#sendAttributeEvent})</li>
+ * <li>User/Client REST initiated ({@link AssetResourceImpl#writeAttributeValue})</li>
+ * <li>User/Client Web Socket initiated ({@link EventService})</li>
+ * <li>Rules Engine ({@link org.openremote.model.rules.Assets#dispatch})</li>
* </ul>
- * The {@link AttributeEvent}s are first validated (link and value type checking) then they are
- * converted into {@link AssetState} messages which are then passed through the processing chain of consumers.
+ * The {@link AttributeEvent}s are first validated using basic validation {@link #validateAttributeEvent} then they are
+ * validated based on sender:
+ * <ul>
+ * <li>User/client - {@link #validateUserRequest}</li>
+ * </ul>
+ * If validation fails at any point then an {@link AssetProcessingException} will be thrown with a
+ * {@link AssetProcessingException.Reason} indicating the cause of validation failure.
+ * <p>
+ * Once successfully validated the event is converted into an {@link AssetState} message which is then passed through
+ * the processing chain of <code>Consumer&lt;AssetState&gt;</code> consumers.
* <p>
* The regular processing chain is:
* <ul>
@@ -87,15 +101,17 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
* is reached.
* <h2>Agent service processing logic</h2>
* <p>
- * When the attribute event came from a Protocol (i.e. generated by a call from
- * {@link org.openremote.agent.protocol.AbstractProtocol#updateLinkedAttribute} then
- * the agent service will ignore the message and just pass it onto the next consumer.
+ * When the {@link AssetState} originates from a protocol sensor update (i.e. generated by a call to
+ * {@link org.openremote.agent.protocol.AbstractProtocol#updateLinkedAttribute} then the agent service will ignore the
+ * message.
+ * <p>
+ * When the {@link AssetState} originates from any other source (including a protocol for arbitrary attribute updates)
+ * then the agent service will validate that the attribute has a valid {@link AssetMeta#AGENT_LINK}.
* <p>
- * When the attribute event came from any other source then the agent service will check if it relates
- * to a {@link AssetType#THING} and if so it will check if the attribute is linked to an {@link AssetType#AGENT}.
- * If it is not linked to an agent then it ignores the message and just passes it to the next consumer. If it
- * is linked to an agent and the agent link is invalid then the message status is set to
- * {@link AssetState.ProcessingStatus#ERROR} and the message will not be able to progress through the processing chain.
+ * If it is not linked to an agent then it ignores the message.
+ * <p>
+ * If it is linked to an agent and the agent link is invalid then the message status is set to
+ * {@link AssetState.ProcessingStatus#HANDLED} and the message will not be able to progress through the processing chain.
* <p>
* If the message is for a valid linked agent then an {@link AttributeEvent} is sent on the
* {@link org.openremote.agent.protocol.AbstractProtocol#ACTUATOR_TOPIC} which the protocol will receive in
@@ -124,7 +140,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// TODO: Some of these options should be configurable depending on expected load etc.
// Message topic for communicating from client to asset/thing layer
- String ASSET_QUEUE = "seda://AssetQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
+ public static final String ASSET_QUEUE = "seda://AssetQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
protected TimerService timerService;
protected ManagerIdentityService managerIdentityService;
@@ -213,22 +229,17 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
.filter(body().isInstanceOf(AttributeEvent.class))
.process(exchange -> {
AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
- String protocolName = exchange.getIn().getHeader(
- Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, "Unknown Protocol", String.class
+ Protocol protocol = exchange.getIn().getHeader(
+ SharedEvent.HEADER_SENDER, Protocol.class
);
- LOG.fine("Received from protocol '" + protocolName + "' on sensor queue: " + event);
-
- ServerAsset asset = assetStorageService.find(event.getEntityId(), true);
- if (asset == null) {
- LOG.warning(
- "Sensor update received from protocol '" + protocolName + "' for an asset that cannot be found: "
- + event.getEntityId()
- );
+ if (protocol == null) {
+ LOG.warning("Sensor update received from a protocol but the protocol is not included in the header");
return;
}
- LOG.fine("Processing sensor " + event + " for asset: " + asset);
+ LOG.fine("Received from protocol '" + protocol.getProtocolName() + "' on sensor queue: " + event);
+ ServerAsset asset = assetStorageService.find(event.getEntityId(), true);
// Get the attribute and check it is actually linked to an agent (although the
// event comes from a Protocol, we can not assume that the attribute is still linked,
@@ -236,168 +247,244 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// for a day)
AssetAttribute attribute = asset.getAttribute(event.getAttributeName()).orElse(null);
- if (attribute == null) {
- LOG.warning(
- "Processing sensor update from protocol '" + protocolName
- + "' failed, no attribute or not linked to an agent: " + event
- );
- return;
- }
+ validateAttributeEvent(event, asset, attribute, true);
- Optional<AssetAttribute> protocolConfiguration =
+ AssetAttribute protocolConfiguration =
getAgentLink(attribute)
- .flatMap(agentService::getProtocolConfiguration);
+ .flatMap(agentService::getProtocolConfiguration)
+ .orElse(null);
- if (!protocolConfiguration.isPresent()) {
+ if (protocolConfiguration == null) {
LOG.warning(
- "Processing sensor update from protocol '" + protocolName
+ "Processing sensor update from protocol '" + protocol.getProtocolName()
+ "' failed, linked agent protocol configuration not found: " + event
);
return;
}
+ if (!protocol.getLinkedProtocolConfigurations().contains(protocolConfiguration)) {
+ LOG.warning("Protocol isn't linked to this protocol configuration: " + protocolConfiguration.getReferenceOrThrow());
+ return;
+ }
+
// Process as non-client source (not southbound)
- processUpdate(asset, attribute, event, false);
+ processUpdate(asset, attribute, event, true, protocol);
});
- // Process arbitrary attribute events
+ // All attribute events (except protocol sensor updates) come through here
from(ASSET_QUEUE)
.filter(body().isInstanceOf(AttributeEvent.class))
.process(exchange -> {
AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
- boolean southbound = exchange.getIn().getHeader(AttributeEvent.HEADER_SOUTHBOUND, true, Boolean.class);
- LOG.fine("Received (southbound: " + southbound + ") on asset queue: " + event);
- updateAttributeValue(event, southbound);
+ Object sender = exchange.getIn().getHeader(SharedEvent.HEADER_SENDER);
+ LOG.fine("Received from '" + sender + "' on asset queue: " + event);
+
+ ServerAsset asset = assetStorageService.find(event.getEntityId(), true);
+ AssetAttribute attribute = asset == null ? null : asset.getAttribute(event.getAttributeName()).orElse(null);
+ validateAttributeEvent(event, asset, attribute, false);
+
+ if (sender instanceof User) {
+ // This is from southbound so ensure user can perform the update
+ User user = (User)sender;
+ validateUserRequest(event, asset, user);
+ } else if (sender instanceof Protocol) {
+ // TODO: implement any protocol specific validation
+ } else if (sender instanceof RulesEngine) {
+ // TODO: implement any rules specific validation
+ }
+
+ processUpdate(asset, attribute, event, false, sender);
});
- // React if a client wants to write attribute state
+ // Client initiated attribute events - sender should always be a user
from(INCOMING_EVENT_TOPIC)
.filter(body().isInstanceOf(AttributeEvent.class))
+ .filter(header(SharedEvent.HEADER_SENDER).isInstanceOf(User.class))
.process(exchange -> {
AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
- LOG.fine("Handling from client: " + event);
+ User user = exchange.getIn().getHeader(SharedEvent.HEADER_SENDER, User.class);
- if (event.getEntityId() == null || event.getEntityId().isEmpty())
- return;
-
- WebsocketAuth auth = getWebsocketAuth(exchange);
-
- // Superuser can write all
- if (auth.isSuperUser()) {
- sendAttributeEvent(event, true);
- return;
- }
-
- // Regular user must have role
- if (!auth.isUserInRole(ClientRole.WRITE_ASSETS.getValue())) {
- return;
- }
-
- ServerAsset asset;
- // Restricted users can only write attribute events for their linked assets
- if (managerIdentityService.isRestrictedUser(auth.getUserId())) {
- if (!assetStorageService.isUserAsset(auth.getUserId(), event.getEntityId()))
- return;
- asset = assetStorageService.find(event.getEntityId(), true, true);
- } else {
- asset = assetStorageService.find(event.getEntityId(), true);
- }
-
- if (asset == null)
- return;
-
- // Attribute must exist
- if (!asset.getAttribute(event.getAttributeName()).isPresent())
- return;
+ LOG.fine("Handling from client: " + event);
- // Regular users can only write attribute events for assets in their realm
- if (!asset.getTenantRealm().equals(auth.getAuthenticatedRealm()))
+ if (event.getEntityId() == null || event.getEntityId().isEmpty() || user == null)
return;
// Put it on the asset queue
- sendAttributeEvent(event, true);
+ sendAttributeEvent(event, user);
});
}
- /**
- * Send attribute change events, with a client origin, into the {@link #ASSET_QUEUE}.
- *
- */
- public void sendAttributeEvent(AttributeEvent attributeEvent) {
- sendAttributeEvent(attributeEvent, true);
- }
-
/**
* Send attribute change events into the {@link #ASSET_QUEUE}.
*
- * @param southBound <code>true</code> if the event origin is a client, and not from a
- * protocol or internal (rules) processing.
+ * The sender indicates the source of the attribute event this should be one of:
+ * <ul>
+ * <li>{@link org.openremote.manager.shared.security.User} - From user/client</li>
+ * <li>{@link Protocol} - From a protocol</li>
+ * <li>{@link org.openremote.manager.server.rules.RulesEngine} - From rules</li>
+ * </ul>
*/
- public void sendAttributeEvent(AttributeEvent attributeEvent, boolean southBound) {
+ public void sendAttributeEvent(AttributeEvent attributeEvent, Object sender) {
messageBrokerService.getProducerTemplate().sendBodyAndHeader(
ASSET_QUEUE,
attributeEvent,
- AttributeEvent.HEADER_SOUTHBOUND,
- southBound
+ SharedEvent.HEADER_SENDER,
+ sender
);
}
- private void updateAttributeValue(AttributeEvent attributeEvent, boolean southBound) {
- // Check this event relates to a valid asset
- ServerAsset asset = assetStorageService.find(attributeEvent.getEntityId(), true);
+ // TODO: Remove this once AssetResourceImpl can get exceptions from camel route
+ public void sendAttributeEventWithoutCamel(AttributeEvent event, Object sender) {
+ LOG.fine("Received from '" + sender + "' on asset queue: " + event);
+
+ ServerAsset asset = assetStorageService.find(event.getEntityId(), true);
+ AssetAttribute attribute = asset == null ? null : asset.getAttribute(event.getAttributeName()).orElse(null);
+ validateAttributeEvent(event, asset, attribute, false);
+
+ if (sender instanceof User) {
+ // This is from southbound so ensure user can perform the update
+ User user = (User)sender;
+ validateUserRequest(event, asset, user);
+ } else if (sender instanceof Protocol) {
+ // TODO: implement any protocol specific validation
+ } else if (sender instanceof RulesEngine) {
+ // TODO: implement any rules specific validation
+ }
+
+ processUpdate(asset, attribute, event, false, sender);
+ }
+
+ // TODO: Update tests to include sender and remove this
+ protected void sendAttributeEvent(AttributeEvent attributeEvent) {
+ sendAttributeEvent(attributeEvent, null);
+ }
+
+ /**
+ * Performs basic validation of all {@link AttributeEvent}s:
+ * <ol>
+ * <li>Check event refers to a valid asset</li>
+ * <li>Check event refers to a valid attribute</li>
+ * <li>Check event doesn't refer to an {@link AssetType#AGENT} Asset</li>
+ * <li>Check that events for executable attributes are of type {@link AttributeExecuteStatus} and are
+ * {@link AttributeExecuteStatus#isWrite} (unless this is a sensor update)</li>
+ * </ol>
+ */
+ protected void validateAttributeEvent(AttributeEvent event, Asset asset, AssetAttribute attribute, boolean isSensorUpdate) throws AssetProcessingException {
if (asset == null) {
- LOG.warning("Processing event failed, asset not found: " + attributeEvent);
- return;
+ LOG.warning("Asset doesn't exist: " + event.getAttributeRef());
+ throw new AssetProcessingException(AssetProcessingException.Reason.ASSET_NOT_FOUND);
+ }
+
+ if (attribute == null) {
+ LOG.warning("Attribute doesn't exist: " + event.getAttributeRef());
+ throw new AssetProcessingException(AssetProcessingException.Reason.ATTRIBUTE_NOT_FOUND);
}
// Prevent editing of individual agent attributes
if (asset.getWellKnownType() == AssetType.AGENT) {
- throw new IllegalArgumentException(
- "Agent attributes can not be updated individually, update the whole asset instead: " + asset
- );
+ LOG.warning("Agent attributes can not be updated individually, update the whole asset instead: " + asset);
+ throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
}
- // Pass attribute event through the processing chain
- LOG.fine("Processing " + attributeEvent + " for: " + asset);
- Optional<AssetAttribute> attribute = asset.getAttribute(attributeEvent.getAttributeName());
+ // Only sensor updates can send AttributeExecuteStatus marked as read values
+ if (!isSensorUpdate && attribute.isExecutable()) {
+ Optional<AttributeExecuteStatus> status = event.getValue()
+ .flatMap(Values::getString)
+ .flatMap(AttributeExecuteStatus::fromString);
- if (!attribute.isPresent()) {
- LOG.warning("Ignoring " + attributeEvent + ", attribute doesn't exist on asset: " + asset);
- return;
+ if (!status.isPresent()) {
+ LOG.warning("Attribute event doesn't contain a valid AttributeExecuteStatus value: " + event);
+ throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
+ }
+
+ if (!status.get().isWrite()) {
+ LOG.warning("Only AttributeExecuteStatus write value can be written to an attribute: " + event);
+ throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
+ }
+ }
+ }
+
+ /**
+ * Performs validation of {@link AttributeEvent}s sent by users/clients:
+ * <p>
+ * All users (including super users):
+ * <ol>
+ * <li>Check asset's realm is valid and active</li>
+ * <li>Check that the event is not for a read only attribute (not even super users are allowed to write to readonly attributes)</li>
+ * </ol>
+ * Additional checks for non super users:
+ * <ol>
+ * <li>User must have {@link ClientRole#WRITE_ASSETS} role</li>
+ * <li>User must be in the same realm as the asset</li>
+ * <li>Restricted users can only write to assets linked to them</li>
+ * <li>Restricted users can only write to attributes marked as protected</li>
+ * </ol>
+ *
+ */
+ protected void validateUserRequest(AttributeEvent event, Asset asset, User user) throws AssetProcessingException {
+
+ // Attribute presence has already been verified
+ //noinspection ConstantConditions
+ AssetAttribute attribute = asset.getAttribute(event.getAttributeName()).get();
+
+ // Check realm is active and accessible
+ Tenant tenant = managerIdentityService.getTenant(asset.getRealmId());
+ if (tenant == null || !tenant.isActive()) {
+ throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
}
// Prevent editing of read only attributes
- if (southBound && attribute.get().isReadOnly()) {
- LOG.warning("Ignoring southbound " + attributeEvent + ", attribute is read-only in: " + asset);
+ if (attribute.isReadOnly()) {
+ LOG.warning("Ignoring southbound " + event + ", attribute is read-only in: " + asset);
+ throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
+ }
+
+ // All other checks only apply to non super user
+ if (user.isSuperUser()) {
return;
}
- // If attribute is marked as executable and southbound only allow write AttributeExecuteStatus to be sent
- if (southBound && attribute.get().isExecutable()) {
- Optional<AttributeExecuteStatus> status = attributeEvent.getValue()
- .flatMap(Values::getString)
- .flatMap(AttributeExecuteStatus::fromString);
+ // Regular user must have write assets role
+ if (!user.hasRole(ClientRole.WRITE_ASSETS.getValue())) {
+ throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
+ }
- if (!status.isPresent()) {
- LOG.warning("Attribute event doesn't contain a valid AttributeExecuteStatus value: " + attributeEvent);
- return;
- }
+ // Regular users can only write attribute events for assets in their realm
+ if (!asset.getTenantRealm().equals(user.getRealm())) {
+ throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
+ }
- if (!status.get().isWrite()) {
- LOG.warning("Only AttributeExecuteStatus write value can be written to an attribute: " + attributeEvent);
- return;
- }
+ // Restricted users can only write attribute events for their linked assets
+ if (user.isRestricted() && !assetStorageService.isUserAsset(user.getId(), asset.getId())) {
+ throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
}
- processUpdate(asset, attribute.get(), attributeEvent, southBound);
+ // Restricted users can only write attribute events for protected attributes
+ if (user.isRestricted() && !attribute.isProtected()) {
+ throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
+ }
}
+ /*
+ * This deals with single attribute value changes and pushes them through the attribute event
+ * processing chain where each consumer is given the opportunity to consume the event or allow
+ * it progress to the next consumer {@link AssetState.ProcessingStatus}.
+ * <p>
+ * NOTE: An attribute value can be changed during Asset CRUD but this does not come through
+ * this route but is handled separately see {@link AssetResourceImpl}. Any attribute values
+ * assigned during Asset CRUD can be thought of as the attributes initial value and is subject
+ * to change by the following actors (depending on attribute meta etc.) All actors use this
+ * entry point to initiate an attribute value change: Sensor updates from protocols, attribute
+ * write requests from protocols, attribute write requests from clients, and attribute write
+ * dispatching as rules RHS action.
+ */
protected void processUpdate(ServerAsset asset,
AssetAttribute attribute,
AttributeEvent attributeEvent,
- boolean southbound) {
+ boolean isSensorUpdate,
+ Object sender) {
// 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)
// Allow a leniency of 1s
@@ -433,32 +520,17 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
return;
}
- processUpdate(
- new AssetState(
+
+ // Push as an asset state through the processing chain
+ AssetState assetState = new AssetState(
asset,
attribute,
lastStateEvent.flatMap(AttributeEvent::getValue).orElse(null),
lastStateEvent.map(AttributeEvent::getTimestamp).orElse(-1L),
- southbound)
- );
- }
+ isSensorUpdate,
+ sender);
- /*
- * This deals with single attribute value changes and pushes them through the attribute event
- * processing chain where each consumer is given the opportunity to consume the event or allow
- * it progress to the next consumer {@link AssetState.ProcessingStatus}.
- * <p>
- * NOTE: An attribute value can be changed during Asset CRUD but this does not come through
- * this route but is handled separately see {@link AssetResourceImpl}. Any attribute values
- * assigned during Asset CRUD can be thought of as the attributes initial value and is subject
- * to change by the following actors (depending on attribute meta etc.) All actors use this
- * entry point to initiate an attribute value change: Sensor updates from protocols, attribute
- * write requests from protocols, attribute write requests from clients, and attribute write
- * dispatching as rules RHS action.
- */
- protected void processUpdate(AssetState assetState) {
try {
- long currentMillis = timerService.getCurrentTimeMillis();
LOG.fine(">>> Processing start " +
"(event time: " + new Date(assetState.getValueTimestamp()) + "/" + assetState.getValueTimestamp() +
", processing time: " + new Date(currentMillis) + "/" + currentMillis
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
index 5294a6f69..520a68f34 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
@@ -19,14 +19,17 @@
*/
package org.openremote.manager.server.asset;
+import org.apache.camel.CamelExecutionException;
+import org.openremote.container.message.MessageBrokerService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.server.web.ManagerWebResource;
+import org.openremote.manager.shared.asset.AssetProcessingException;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.manager.shared.security.Tenant;
+import org.openremote.manager.shared.security.User;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetQuery;
-import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.value.Value;
@@ -47,13 +50,16 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
protected final AssetStorageService assetStorageService;
protected final AssetProcessingService assetProcessingService;
+ protected final MessageBrokerService messageBrokerService;
public AssetResourceImpl(ManagerIdentityService identityService,
AssetStorageService assetStorageService,
- AssetProcessingService assetProcessingService) {
+ AssetProcessingService assetProcessingService,
+ MessageBrokerService messageBrokerService) {
super(identityService);
this.assetStorageService = assetStorageService;
this.assetProcessingService = assetProcessingService;
+ this.messageBrokerService = messageBrokerService;
}
@Override
@@ -226,51 +232,49 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
@Override
public void writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, String rawJson) {
try {
-
ServerAsset asset;
+ User user = identityService.getUser(getAccessToken());
- if (isRestrictedUser()) {
- asset = assetStorageService.find(assetId, true, true);
- if (asset == null)
- throw new WebApplicationException(NOT_FOUND);
-
- if (!assetStorageService.isUserAsset(getUserId(), assetId))
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ Value value = Values.instance()
+ .parse(rawJson)
+ .orElse(null); // When parsing literal JSON "null"
- } else {
- asset = assetStorageService.find(assetId, true);
- if (asset == null)
- throw new WebApplicationException(NOT_FOUND);
- }
+ AttributeEvent event = new AttributeEvent(new AttributeRef(assetId, attributeName), value);
- // Check attribute exists
- if (!asset.hasAttribute(attributeName))
- throw new WebApplicationException(NOT_FOUND);
+ // TODO: Get this working using camel route
+ assetProcessingService.sendAttributeEventWithoutCamel(event, user);
- // Check realm, must be accessible
- if (!isTenantActiveAndAccessible(asset)) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't update: " + assetId);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
- }
+// messageBrokerService
+// .getProducerTemplate()
+// .sendBodyAndHeader(INCOMING_EVENT_TOPIC, event, SharedEvent.HEADER_SENDER, user);
- // Check read-only
- if (!isSuperUser() && asset.getAttributesStream().anyMatch(attribute -> Attribute.isAttributeNameEqualTo(attribute, attributeName) && attribute.isReadOnly())) {
- throw new WebApplicationException(Response.Status.FORBIDDEN);
+ } catch (AssetProcessingException assetProcessingException) {
+ switch (assetProcessingException.getReason()) {
+ case INSUFFICIENT_ACCESS:
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ case ASSET_NOT_FOUND:
+ throw new WebApplicationException(NOT_FOUND);
+ case ATTRIBUTE_NOT_FOUND:
+ throw new WebApplicationException(NOT_FOUND);
+ case INVALID_ACTION:
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
-
- // Process update
- try {
- Value value = Values.instance()
- .parse(rawJson)
- .orElse(null); // When parsing literal JSON "null"
- assetProcessingService.sendAttributeEvent(
- new AttributeEvent(new AttributeRef(assetId, attributeName), value)
- );
- } catch (RuntimeException ex) {
- throw new IllegalStateException("Error updating attribute: " + attributeName, ex);
+ } catch (CamelExecutionException ex) {
+ // Unwrap the exception
+ Throwable cause = ex.getCause();
+ if (cause instanceof AssetProcessingException) {
+ AssetProcessingException assetProcessingException = (AssetProcessingException)cause;
+ switch (assetProcessingException.getReason()) {
+ case INSUFFICIENT_ACCESS:
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ case ASSET_NOT_FOUND:
+ throw new WebApplicationException(NOT_FOUND);
+ case ATTRIBUTE_NOT_FOUND:
+ throw new WebApplicationException(NOT_FOUND);
+ }
}
-
- } catch (IllegalStateException ex) {
+ throw new IllegalStateException("Error updating attribute: " + attributeName, ex);
+ } catch (Exception ex) {
throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
index c69aa80ed..6d1668d71 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
@@ -24,19 +24,21 @@ import org.hibernate.Session;
import org.hibernate.jdbc.AbstractReturningWork;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
+import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.timer.TimerService;
import org.openremote.container.web.WebService;
-import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.manager.server.event.EventService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.security.ClientRole;
import org.openremote.manager.shared.security.Tenant;
+import org.openremote.manager.shared.security.User;
import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.util.Pair;
import org.openremote.model.value.Value;
import org.postgresql.util.PGobject;
@@ -50,7 +52,8 @@ import java.util.stream.Collectors;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
-import static org.openremote.manager.server.event.EventService.*;
+import static org.openremote.manager.server.event.EventService.INCOMING_EVENT_TOPIC;
+import static org.openremote.manager.server.event.EventService.getSessionKey;
public class AssetStorageService extends RouteBuilder implements ContainerService, Consumer<AssetState> {
@@ -102,7 +105,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
new AssetResourceImpl(
managerIdentityService,
this,
- container.getService(AssetProcessingService.class)
+ container.getService(AssetProcessingService.class),
+ container.getService(MessageBrokerService.class)
)
);
@@ -145,39 +149,30 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// React if a client wants to read attribute state
from(INCOMING_EVENT_TOPIC)
.filter(body().isInstanceOf(ReadAssetAttributesEvent.class))
+ .filter(header(SharedEvent.HEADER_SENDER).isInstanceOf(User.class))
.process(exchange -> {
+ String sessionKey = getSessionKey(exchange);
ReadAssetAttributesEvent event = exchange.getIn().getBody(ReadAssetAttributesEvent.class);
+ User user = exchange.getIn().getHeader(SharedEvent.HEADER_SENDER, User.class);
LOG.fine("Handling from client: " + event);
- if (event.getAssetId() == null || event.getAssetId().isEmpty())
+ if (event.getAssetId() == null || event.getAssetId().isEmpty() || user == null)
return;
- String sessionKey = getSessionKey(exchange);
- WebsocketAuth auth = getWebsocketAuth(exchange);
-
- // Superuser can get all
- if (auth.isSuperUser()) {
- ServerAsset asset = find(event.getAssetId(), true);
- if (asset != null)
- replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());
- return;
- }
-
- // User must have role
- if (!auth.isUserInRole(ClientRole.READ_ASSETS.getValue())) {
+ if (!user.isSuperUser() && !user.hasRole(ClientRole.READ_ASSETS.getValue())) {
return;
}
ServerAsset asset = find(
event.getAssetId(),
true,
- managerIdentityService.isRestrictedUser(auth.getUserId()) // Restricted users get filtered state
+ user.isRestricted() // Restricted users get filtered state
);
+
if (asset != null) {
replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());
}
});
-
}
public ServerAsset find(String assetId) {
@@ -687,6 +682,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
+
protected void replyWithAttributeEvents(String sessionKey, ServerAsset asset, String[] attributeNames) {
List<String> names = attributeNames == null ? Collections.emptyList() : Arrays.asList(attributeNames);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
index c6cb114bf..3177ed883 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
@@ -28,7 +28,11 @@ import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.timer.TimerService;
import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.container.web.socket.WebsocketConstants;
+import org.openremote.manager.server.asset.AssetProcessingService;
+import org.openremote.manager.server.asset.AssetStorageService;
import org.openremote.manager.server.concurrent.ManagerExecutorService;
+import org.openremote.manager.server.security.ManagerIdentityService;
+import org.openremote.manager.shared.security.User;
import org.openremote.model.event.shared.CancelEventSubscription;
import org.openremote.model.event.shared.EventSubscription;
import org.openremote.model.event.shared.SharedEvent;
@@ -101,17 +105,24 @@ public class EventService implements ContainerService {
final protected Collection<EventSubscriptionAuthorizer> eventSubscriptionAuthorizers = new CopyOnWriteArraySet<>();
protected MessageBrokerService messageBrokerService;
+ protected ManagerIdentityService managerIdentityService;
+ protected AssetStorageService assetStorageService;
+ protected AssetProcessingService assetProcessingService;
protected EventSubscriptions eventSubscriptions;
@Override
public void init(Container container) throws Exception {
messageBrokerService = container.getService(MessageBrokerService.class);
+ managerIdentityService = container.getService(ManagerIdentityService.class);
+ assetStorageService = container.getService(AssetStorageService.class);
+ assetProcessingService = container.getService(AssetProcessingService.class);
eventSubscriptions = new EventSubscriptions(
container.getService(TimerService.class),
container.getService(ManagerExecutorService.class)
);
+
MessageBrokerSetupService messageBrokerSetupService = container.getService(MessageBrokerSetupService.class);
messageBrokerSetupService.getContext().getTypeConverterRegistry().addTypeConverters(
new EventTypeConverters()
@@ -165,7 +176,18 @@ public class EventService implements ContainerService {
})
.when(bodyAs(String.class).startsWith(SharedEvent.MESSAGE_PREFIX))
.convertBodyTo(SharedEvent.class)
- .to(EventService.INCOMING_EVENT_TOPIC)
+ .process(exchange -> {
+ WebsocketAuth auth = getWebsocketAuth(exchange);
+
+ // Extract user object to use as the sender
+ User user = managerIdentityService.getUser(auth.getAccessToken());
+
+ // TODO: There's probably a better way of doing this in camel
+ SharedEvent event = exchange.getIn().getBody(SharedEvent.class);
+ messageBrokerService
+ .getProducerTemplate()
+ .sendBodyAndHeader(INCOMING_EVENT_TOPIC, event, SharedEvent.HEADER_SENDER, user);
+ })
.otherwise()
.process(exchange -> LOG.fine("Unsupported message body: " + exchange.getIn().getBody()))
.end();
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java
index 83023ce68..a649a988d 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java
@@ -635,7 +635,7 @@ public class RulesEngine<T extends Ruleset> {
}
LOG.fine("Dispatching on " + RulesEngine.this + ": " + event);
- assetProcessingService.sendAttributeEvent(event, false);
+ assetProcessingService.sendAttributeEvent(event, RulesEngine.this);
}
}
};
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
index 8186cd074..5715668f9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
@@ -172,7 +172,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
.forEach(pair -> {
ServerAsset asset = pair.key;
pair.value.forEach(ruleAttribute -> {
- AssetState assetState = new AssetState(asset, ruleAttribute);
+ AssetState assetState = new AssetState(asset, ruleAttribute, false, null);
// Set the status to completed already so rules cannot interfere with this initial insert
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
updateAssetState(assetState, true);
@@ -254,7 +254,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
BiFunction<Asset, AssetAttribute, AssetState> buildAssetState = (loadedAsset, attribute) ->
new AssetState(loadedAsset,
- attribute.deepCopy()
+ attribute.deepCopy(),
+ false,
+ null
);
Asset loadedAsset;
@@ -359,7 +361,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
.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
- AssetState assetState = new AssetState(asset, attribute);
+ AssetState assetState = new AssetState(asset, attribute, false, null);
LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + assetState);
retractAssetState(assetState);
});
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
index fded1163c..953f2b2ef 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
@@ -23,9 +23,11 @@ import org.apache.camel.ExchangePattern;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ClientsResource;
import org.keycloak.admin.client.resource.RolesResource;
+import org.keycloak.representations.AccessToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
+import org.keycloak.representations.idm.UserRepresentation;
import org.openremote.container.Container;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.persistence.PersistenceEvent;
@@ -45,8 +47,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
-import static org.openremote.model.Constants.*;
import static org.openremote.manager.server.util.JsonUtil.convert;
+import static org.openremote.model.Constants.*;
+import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
public class ManagerIdentityService extends IdentityService {
@@ -239,6 +242,59 @@ public class ManagerIdentityService extends IdentityService {
});
}
+ // TODO: Have a single getUser method that gets all data in a single query
+
+ /**
+ * Get user from their Keycloak {@link UserRepresentation}
+ */
+ public User getUser(String realm, UserRepresentation userRepresentation) {
+ User user = convert(Container.JSON, User.class, userRepresentation);
+ user.setRealm(realm);
+ populateUserConfiguration(user);
+ return user;
+ }
+
+ /**
+ * Get user from their Keycloak {@link AccessToken}
+ */
+ public User getUser(AccessToken accessToken) {
+ String realm = accessToken.getIssuer().substring(accessToken.getIssuer().lastIndexOf('/') + 1);
+ requireNonNullAndNonEmpty(realm);
+ User user = new User();
+ user.setId(accessToken.getSubject());
+ user.setUsername(accessToken.getPreferredUsername());
+ user.setClient(accessToken.getIssuedFor());
+ user.setRealm(realm);
+ user.setFirstName(accessToken.getGivenName());
+ user.setLastName(accessToken.getFamilyName());
+ user.setEmail(accessToken.getEmail());
+ user.setEnabled(accessToken.isActive()); // If they have an active token then they're enabled
+ user.setRealmRoles(new ArrayList<>(accessToken.getRealmAccess().getRoles()));
+ accessToken.getResourceAccess()
+ .forEach(
+ (client, clientRoles) -> {
+ user.addClientRoles(client, new ArrayList<>(clientRoles.getRoles()));
+ }
+ );
+ populateUserConfiguration(user);
+ return user;
+ }
+
+ /**
+ * Get user from their ID
+ */
+ // TODO: populate missing data
+ public User getUser(String userId, boolean loadComplete) {
+ return persistenceService.doReturningTransaction(em -> {
+ return em.find(User.class, userId);
+ });
+ }
+
+ protected void populateUserConfiguration(User user) {
+ UserConfiguration userConfiguration = getUserConfiguration(user.getId());
+ user.setRestricted(userConfiguration.isRestricted());
+ }
+
/**
* Use PERSISTENCE_TOPIC and persistence event
*/
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
index d1cb2eb49..78f7819b5 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
@@ -68,7 +68,7 @@ public class UserResourceImpl extends WebResource implements UserResource {
.realm(realm).users().search(null, 0, Integer.MAX_VALUE);
List<User> users = new ArrayList<>();
for (UserRepresentation userRepresentation : userRepresentations) {
- users.add(convertUser(realm, userRepresentation));
+ users.add(identityService.getUser(realm, userRepresentation));
}
return users.toArray(new User[users.size()]);
} catch (ClientErrorException ex) {
@@ -84,7 +84,7 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- return convertUser(
+ return identityService.getUser(
realm,
identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
.realm(realm).users().get(userId).toRepresentation()
@@ -281,12 +281,6 @@ public class UserResourceImpl extends WebResource implements UserResource {
}
}
- protected User convertUser(String realm, UserRepresentation userRepresentation) {
- User user = convert(Container.JSON, User.class, userRepresentation);
- user.setRealm(realm);
- return user;
- }
-
protected ConstraintViolationReport isIllegalMasterAdminUserDeletion(RequestParams requestParams, String realm, String userId) {
if (!realm.equals(MASTER_REALM))
return null;
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
index 0b3493758..5115bb390 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
@@ -256,54 +256,54 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
AssetAttribute light1PowerConsumptionAttribute = thing.getAttribute("light1PowerConsumption")
.orElseThrow(() -> new RuntimeException("Invalid test data"));
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(0.11), now.minusDays(80).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(1.22), now.minusDays(40).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(2.33), now.minusDays(20).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(3.44), now.minusDays(10).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(4.55), now.minusDays(8).toEpochSecond() * 1000);
light1PowerConsumptionAttribute.setValue(Values.create(5.66), now.minusDays(6).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(6.77), now.minusDays(3).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(7.88), now.minusDays(1).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(8.99), now.minusHours(10).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(9.11), now.minusHours(5).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(10.22), now.minusHours(2).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(11.33), now.minusHours(1).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
light1PowerConsumptionAttribute.setValue(Values.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, null));
// ################################ Demo assets for 'customerA' realm ###################################
@@ -430,6 +430,9 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
ServerAsset apartment3Livingroom = new ServerAsset("Living Room", ROOM, apartment3);
apartment3Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));
+ apartment3Livingroom.addAttributes(
+ new AssetAttribute("lightSwitch", AttributeType.BOOLEAN)
+ );
apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);
apartment3LivingroomId = apartment3Livingroom.getId();
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetProcessingException.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetProcessingException.java
new file mode 100644
index 000000000..b41b4f71e
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetProcessingException.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.shared.asset;
+
+public class AssetProcessingException extends RuntimeException {
+ public enum Reason {
+ INSUFFICIENT_ACCESS,
+ ASSET_NOT_FOUND,
+ ATTRIBUTE_NOT_FOUND,
+ INVALID_ACTION
+ }
+
+ protected Reason reason;
+
+ public AssetProcessingException(Reason reason) {
+ this.reason = reason;
+ }
+
+ public Reason getReason() {
+ return reason;
+ }
+}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java
index c6faede7f..75dce09ef 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java
@@ -22,6 +22,7 @@ package org.openremote.manager.shared.security;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.Subselect;
import org.hibernate.validator.constraints.Email;
+import org.openremote.model.Constants;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -30,6 +31,7 @@ import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
+import java.util.*;
/**
* This can be used (among other things) to query the Keycloak USER_ENTITY table in JPA queries.
@@ -62,6 +64,21 @@ public class User {
@Column(name = "ENABLED")
protected Boolean enabled;
+ // TODO: Extract this data from the SQL view when not available in access token
+ @Transient
+ protected String client;
+
+ // TODO: Extract this data from the SQL view when not available in access token
+ @Transient
+ protected Map<String, List<String>> clientRoles;
+
+ // TODO: Extract this data from the SQL view when not available in access token
+ @Transient
+ protected List<String> realmRoles;
+
+ @Formula("(select u.RESTRICTED from USER_CONFIGURATION u where u.USER_ID = ID)")
+ protected boolean restricted;
+
public User() {
}
@@ -135,6 +152,64 @@ public class User {
this.enabled = enabled;
}
+ public Set<String> getRoles() {
+ List<String> roles = clientRoles != null ? clientRoles.get(client) : null;
+ return roles != null ? new HashSet<>(roles) : Collections.emptySet();
+ }
+
+ public Map<String, List<String>> getClientRoles() {
+ return clientRoles;
+ }
+
+ public void setClientRoles(Map<String, List<String>> clientRoles) {
+ this.clientRoles = clientRoles;
+ }
+
+ public void addClientRoles(String client, List<String> roles) {
+ if (client != null) {
+ if (clientRoles == null) {
+ clientRoles = new HashMap<>();
+ }
+ clientRoles.put(client, roles);
+ }
+ }
+
+ public List<String> getRealmRoles() {
+ return realmRoles;
+ }
+
+ public void setRealmRoles(List<String> realmRoles) {
+ this.realmRoles = realmRoles;
+ }
+
+ public String getClient() {
+ return client;
+ }
+
+ public void setClient(String client) {
+ this.client = client;
+ }
+
+ public boolean isRestricted() {
+ return !isSuperUser() && restricted;
+ }
+
+ public void setRestricted(boolean restricted) {
+ this.restricted = restricted;
+ }
+
+ public boolean isSuperUser() {
+ return getRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);
+ }
+
+ public boolean hasRole(String role) {
+ return getRoles() != null && getRoles().contains(role);
+ }
+
+ public boolean hasRealmRole(String role) {
+ return getRealmRoles() != null && getRealmRoles().contains(role);
+ }
+
@Override
public String toString() {
return getClass().getName() + "{" +
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
index 37c0ed58e..71b617da5 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.asset;
+import org.kie.api.task.model.User;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeType;
@@ -71,13 +72,15 @@ public abstract class AbstractAssetUpdate {
final protected long oldValueTimestamp;
- protected boolean southbound;
+ final protected boolean sensorUpdate;
- public AbstractAssetUpdate(Asset asset, AssetAttribute attribute) {
- this(asset, attribute, null, 0, false);
+ final protected Object sender;
+
+ public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, boolean sensorUpdate, Object sender) {
+ this(asset, attribute, null, 0, sensorUpdate, sender);
}
- public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean southbound) {
+ public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean sensorUpdate, Object sender) {
this(
attribute,
asset.getCreatedOn(),
@@ -95,7 +98,8 @@ public abstract class AbstractAssetUpdate {
asset.getCoordinates(),
oldValue,
oldValueTimestamp,
- southbound
+ sensorUpdate,
+ sender
);
}
@@ -117,7 +121,8 @@ public abstract class AbstractAssetUpdate {
that.coordinates,
that.oldValue,
that.oldValueTimestamp,
- that.southbound
+ that.sensorUpdate,
+ that.sender
);
}
@@ -128,7 +133,8 @@ public abstract class AbstractAssetUpdate {
double[] coordinates,
Value oldValue,
long oldValueTimestamp,
- boolean southbound) {
+ boolean sensorUpdate,
+ Object sender) {
this.attribute = attribute;
this.createdOn = createdOn;
this.id = id;
@@ -148,7 +154,8 @@ public abstract class AbstractAssetUpdate {
this.coordinates = coordinates;
this.oldValue = oldValue;
this.oldValueTimestamp = oldValueTimestamp;
- this.southbound = southbound;
+ this.sensorUpdate = sensorUpdate;
+ this.sender = sender;
}
public Date getCreatedOn() {
@@ -212,11 +219,15 @@ public abstract class AbstractAssetUpdate {
}
/**
- * True if the update was initiated by a client (and not protocol or internal) and
+ * True if the update was initiated by a user/client (and not protocol or internal) and
* is being processed southbound.
*/
public boolean isSouthbound() {
- return southbound;
+ return sender == null || sender instanceof User;
+ }
+
+ public boolean isSensorUpdate() {
+ return sensorUpdate;
}
public Value getValue() {
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index 86da3094b..b1c55c376 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -340,6 +340,10 @@ public class Asset implements IdentifiableEntity {
public void addAttributes(AssetAttribute... attributes) throws IllegalArgumentException {
+ if (this.attributes == null) {
+ this.attributes = Values.createObject();
+ }
+
Arrays.asList(attributes).forEach(
attribute -> {
if (getAttributesStream().anyMatch(attr -> isAttributeNameEqualTo(attr, attribute.getName().orElse(null)))) {
@@ -352,6 +356,10 @@ public class Asset implements IdentifiableEntity {
}
public void replaceAttribute(AssetAttribute attribute) throws IllegalArgumentException {
+ if (attributes == null) {
+ return;
+ }
+
if (attribute == null || !attribute.getName().isPresent() || !attribute.getType().isPresent())
throw new IllegalArgumentException("Attribute cannot be null and must have a name and type");
@@ -363,6 +371,10 @@ public class Asset implements IdentifiableEntity {
}
public void removeAttribute(String name) {
+ if (attributes == null) {
+ return;
+ }
+
attributes.remove(name);
}
@@ -551,11 +563,11 @@ public class Asset implements IdentifiableEntity {
}
public boolean hasAttribute(String name) {
- return attributes.hasKey(name);
+ return attributes != null && attributes.hasKey(name);
}
public Optional<AssetAttribute> getAttribute(String name) {
- return attributes.getObject(name)
+ return attributes == null ? Optional.empty() : attributes.getObject(name)
.flatMap(objectValue -> AssetAttribute.attributeFromJson(objectValue, id, name));
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetState.java b/model/src/main/java/org/openremote/model/asset/AssetState.java
index 74628e947..a0144ca17 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetState.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetState.java
@@ -61,12 +61,12 @@ public class AssetState extends AbstractAssetUpdate {
protected Throwable error;
- public AssetState(Asset asset, AssetAttribute attribute) {
- super(asset, attribute);
+ public AssetState(Asset asset, AssetAttribute attribute, boolean isSensorUpdate, Object sender) {
+ super(asset, attribute, isSensorUpdate, sender);
}
- public AssetState(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean southbound) {
- super(asset, attribute, oldValue, oldValueTimestamp, southbound);
+ public AssetState(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean isSensorUpdate, Object sender) {
+ super(asset, attribute, oldValue, oldValueTimestamp, isSensorUpdate, sender);
}
public ProcessingStatus getProcessingStatus() {
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
index cc59875b1..4a115a78f 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
@@ -31,8 +31,6 @@ import java.util.Optional;
*/
public class AttributeEvent extends SharedEvent {
- public static final String HEADER_SOUTHBOUND = AttributeEvent.class.getName() + ".SOUTHBOUND";
-
public static class EntityIdFilter extends EventFilter<AttributeEvent> {
public static final String FILTER_TYPE = "attribute-entity-id";
diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
index 23a1c6ceb..751ed5b9e 100644
--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
@@ -22,9 +22,9 @@ package org.openremote.model.event.shared;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.asset.ReadAssetAttributesEvent;
import org.openremote.model.asset.AssetTreeModifiedEvent;
+import org.openremote.model.asset.ReadAssetAttributesEvent;
+import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.event.Event;
import org.openremote.model.syslog.SyslogEvent;
@@ -52,6 +52,7 @@ import org.openremote.model.syslog.SyslogEvent;
)
public abstract class SharedEvent extends Event {
+ public static final String HEADER_SENDER = SharedEvent.class.getName() + ".SENDER";
public static final String MESSAGE_PREFIX = "EVENT";
public SharedEvent(long timestamp) {