Skip to content

armgit / core

Public Imported from GitHub
0

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

Rules service now listening to tenant changes

Rich Turner2fc3911b4060
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 043fceda2..2c6a3099e 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
@@ -40,6 +40,7 @@ import java.sql.ResultSet;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import static org.openremote.model.asset.AssetType.AGENT;
@@ -307,6 +308,23 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
}
}
+ public String[] getAssetRealmIds(List<String> assetIds) {
+ if (assetIds == null || assetIds.size() == 0) {
+ return new String[0];
+ }
+
+ return persistenceService.doReturningTransaction(entityManager -> {
+ List<String> results = entityManager.createQuery(
+ "select a.realmId " +
+ "from Asset a " +
+ "where a.id IN :ids")
+ .setParameter("ids", assetIds)
+ .getResultList();
+ return results
+ .toArray(new String[0]);
+ });
+ }
+
protected ServerAsset loadAsset(EntityManager em, String assetId, boolean loadDetails) {
ServerAsset asset = em.find(ServerAsset.class, assetId);
if (asset == null)
@@ -387,6 +405,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
);
}
+
public String toString() {
return getClass().getSimpleName() + "{" +
'}';
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
index bc795f547..0ff5609c9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
@@ -237,6 +237,22 @@ public class RulesDeployment<T extends RulesDefinition> {
kfs.delete("src/main/resources/" + rulesDefinition.getId());
ruleDefinitions.remove(rulesDefinition.getId());
+ // Update status of each rules definition
+ boolean anyFailed = ruleDefinitions
+ .values()
+ .stream()
+ .anyMatch(rd -> rd.getDeploymentStatus() == RulesDefinition.DeploymentStatus.FAILED);
+
+ error = anyFailed;
+
+ if (!anyFailed) {
+ ruleDefinitions.forEach((id, rd) -> {
+ if (rd.getDeploymentStatus() == RulesDefinition.DeploymentStatus.READY) {
+ rd.setDeploymentStatus(RulesDefinition.DeploymentStatus.DEPLOYED);
+ }
+ });
+ }
+
if (!isError() && !isEmpty()) {
// Queue engine start
startTimer = executorService.schedule(this::start, AUTO_START_DELAY_SECONDS, TimeUnit.SECONDS);
@@ -294,6 +310,7 @@ public class RulesDeployment<T extends RulesDefinition> {
LOG.fine("Stopping RuleEngine: " + this);
if (knowledgeSession != null) {
+ knowledgeSession.halt();
knowledgeSession.dispose();
kb = null;
LOG.fine("Knowledge session disposed");
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 9f1d211b5..ef4f7a231 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
@@ -31,7 +31,9 @@ import org.openremote.manager.server.asset.AssetUpdate;
import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.rules.*;
+import org.openremote.manager.shared.security.Tenant;
import org.openremote.model.Consumer;
+import org.openremote.model.asset.Asset;
import java.util.*;
import java.util.logging.Logger;
@@ -52,9 +54,6 @@ import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceE
* asset definitions with same parent asset are not guaranteed also processing of definitions
* with the same scope is not guaranteed)
*/
-// TODO: Listen to changes in tenant enabled status and start/stop engines accordingly
-// TODO: Listen to asset changes and start/stop engines accordingly
-// TODO: When restarting rules engine should we wait for executing rules to finish?
public class RulesService extends RouteBuilder implements ContainerService, Consumer<AssetUpdate> {
private static final Logger LOG = Logger.getLogger(RulesService.class.getName());
protected PersistenceService persistenceService;
@@ -64,7 +63,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected RulesDeployment<GlobalRulesDefinition> globalDeployment;
protected final Map<String, RulesDeployment<TenantRulesDefinition>> tenantDeployments = new HashMap<>();
protected final Map<String, RulesDeployment<AssetRulesDefinition>> assetDeployments = new HashMap<>();
- protected String[] activeTenantNames;
+ protected String[] activeTenantRealmIds;
@Override
public void init(Container container) throws Exception {
@@ -77,18 +76,29 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
@Override
public void configure() throws Exception {
+ // If any rules definition was modified in the database then check its' status and retract, insert or update it
from(PERSISTENCE_TOPIC)
.filter(isPersistenceEventForEntityType(RulesDefinition.class))
.process(exchange -> {
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
processRulesDefinitionChange((RulesDefinition)persistenceEvent.getEntity(), persistenceEvent.getCause());
});
+
+ // If any tenant was modified in the database then check its' status and retract, insert or update any
+ // associated rule definitions
+ from(PERSISTENCE_TOPIC)
+ .filter(isPersistenceEventForEntityType(Tenant.class))
+ .process(exchange -> {
+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
+ Tenant tenant = (Tenant) persistenceEvent.getEntity();
+ processTenantChange(tenant, persistenceEvent.getCause());
+ });
}
@Override
public void start(Container container) throws Exception {
// Get active tenants
- String[] activeTenantRealmIds = identityService.getActiveTenantRealmIds();
+ activeTenantRealmIds = identityService.getActiveTenantRealmIds();
// Deploy global rules
List<GlobalRulesDefinition> enabledGlobalDefinitions = rulesStorageService.findEnabledGlobalDefinitions();
@@ -123,39 +133,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
// Deploy asset rules - group by assetID then tenant then order hierarchically
- rulesStorageService.findAllEnabledAssetDefinitions()
- .stream()
- .collect(Collectors.groupingBy(AssetRulesDefinition::getAssetId))
- .entrySet()
- .stream()
- .map(es ->
- new Pair<>(assetStorageService.find(es.getKey()), es.getValue())
- )
- .collect(Collectors.groupingBy(assetAndRules -> assetAndRules.key.getRealmId()))
- .entrySet()
- .stream()
- .filter(es -> Arrays
- .stream(activeTenantRealmIds)
- .anyMatch(at -> es.getKey().equals(at)))
- .forEach(es -> {
- List<Pair<ServerAsset, List<AssetRulesDefinition>>> tenantAssetAndRules = es.getValue();
-
- // Order rules definitions by asset hierarchy within this tenant
- tenantAssetAndRules.stream()
- .sorted(Comparator.comparingInt(item -> item.key.getPath().length))
- .forEach(assetAndRules -> {
- List<AssetRulesDefinition> rulesDefinitions = assetAndRules.value;
- String[] assetRules = rulesStorageService.getRules(rulesDefinitions, AssetRulesDefinition.class);
-
- if (assetRules.length != rulesDefinitions.size()) {
- LOG.warning("Failed to retrieve asset rules definitions");
- } else {
- IntStream
- .range(0, assetRules.length)
- .forEach(i -> deployAssetRulesDefinition(rulesDefinitions.get(i), assetRules[i]));
- }
- });
- });
+ deployAssetRulesDefinitions(rulesStorageService.findAllEnabledAssetDefinitions());
}
@Override
@@ -179,12 +157,65 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
processAssetUpdate(assetUpdate);
}
- public void processTenantChange() {
+ public synchronized void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {
+ // Check if enabled status has changed
+ boolean wasEnabled = Arrays.asList(activeTenantRealmIds).contains(tenant.getId());
+ boolean isEnabled = tenant.getEnabled() && cause != PersistenceEvent.Cause.DELETE;
+ activeTenantRealmIds = identityService.getActiveTenantRealmIds();
+
+ if (wasEnabled == isEnabled) {
+ // Nothing to do here
+ return;
+ }
+
+ if (wasEnabled) {
+ // Remove tenant deployment for this tenant if it exists
+ RulesDeployment<TenantRulesDefinition> tenantDeployment = tenantDeployments.get(tenant.getId());
+ if (tenantDeployment != null) {
+ Arrays.stream(tenantDeployment.getAllRulesDefinitions())
+ .forEach(rd -> retractTenantRulesDefinition(rd));
+ }
+ // Remove any asset deployments for assets in this realm
+ List<String> assetIds = new ArrayList<>(assetDeployments.keySet());
+ String[] realmIds = assetStorageService.getAssetRealmIds(assetIds);
+
+ if (realmIds.length != assetDeployments.size()) {
+ LOG.warning("Failed to retrieve asset realm ids");
+ } else {
+ for (int i=0; i<realmIds.length; i++) {
+ String realmId = realmIds[i];
+ if (realmId != null && realmId.equals(tenant.getId())) {
+ RulesDeployment<AssetRulesDefinition> assetDeployment = assetDeployments.get(assetIds.get(i));
+ Arrays.stream(assetDeployment.getAllRulesDefinitions())
+ .forEach(rd -> retractAssetRulesDefinition(rd));
+ }
+ }
+ }
+ } else {
+ // Insert tenant deployment for this tenant if it has any rule definitions
+ List<TenantRulesDefinition> enabledTenantDefinitions = rulesStorageService
+ .findTenantDefinitions(tenant.getId())
+ .stream()
+ .filter(rd -> rd.isEnabled())
+ .collect(Collectors.toList());
+ String[] tenantRules = rulesStorageService.getRules(enabledTenantDefinitions, TenantRulesDefinition.class);
+
+ if (tenantRules.length != enabledTenantDefinitions.size()) {
+ LOG.warning("Failed to retrieve tenant rules definitions");
+ } else {
+ IntStream
+ .range(0, tenantRules.length)
+ .forEach(i -> deployTenantRulesDefinition(enabledTenantDefinitions.get(i), tenantRules[i]));
+ }
+
+ // Insert any asset deployments for assets in this realm that have rule definitions
+ deployAssetRulesDefinitions(rulesStorageService.findAllEnabledAssetDefinitions(tenant.getId()));
+ }
}
protected void processRulesDefinitionChange(RulesDefinition rulesDefinition, PersistenceEvent.Cause cause) {
- if (cause == PersistenceEvent.Cause.DELETE) {
+ if (cause == PersistenceEvent.Cause.DELETE || !rulesDefinition.isEnabled()) {
if (rulesDefinition instanceof GlobalRulesDefinition) {
retractGlobalRulesDefinition((GlobalRulesDefinition)rulesDefinition);
} else if (rulesDefinition instanceof TenantRulesDefinition) {
@@ -194,7 +225,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
} else {
if (rulesDefinition instanceof GlobalRulesDefinition) {
- deployGlobalRulesDefinition((GlobalRulesDefinition)rulesDefinition, rulesStorageService.getRules((GlobalRulesDefinition)rulesDefinition, GlobalRulesDefinition.class));
+ deployGlobalRulesDefinition((GlobalRulesDefinition) rulesDefinition, rulesStorageService.getRules((GlobalRulesDefinition) rulesDefinition, GlobalRulesDefinition.class));
} else if (rulesDefinition instanceof TenantRulesDefinition) {
deployTenantRulesDefinition((TenantRulesDefinition)rulesDefinition, rulesStorageService.getRules((TenantRulesDefinition)rulesDefinition, TenantRulesDefinition.class));
} else if (rulesDefinition instanceof AssetRulesDefinition) {
@@ -294,6 +325,42 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
}
+ protected void deployAssetRulesDefinitions(List<AssetRulesDefinition> assetRulesDefinitions) {
+ assetRulesDefinitions
+ .stream()
+ .collect(Collectors.groupingBy(AssetRulesDefinition::getAssetId))
+ .entrySet()
+ .stream()
+ .map(es ->
+ new Pair<>(assetStorageService.find(es.getKey()), es.getValue())
+ )
+ .collect(Collectors.groupingBy(assetAndRules -> assetAndRules.key.getRealmId()))
+ .entrySet()
+ .stream()
+ .filter(es -> Arrays
+ .stream(activeTenantRealmIds)
+ .anyMatch(at -> es.getKey().equals(at)))
+ .forEach(es -> {
+ List<Pair<ServerAsset, List<AssetRulesDefinition>>> tenantAssetAndRules = es.getValue();
+
+ // Order rules definitions by asset hierarchy within this tenant
+ tenantAssetAndRules.stream()
+ .sorted(Comparator.comparingInt(item -> item.key.getPath().length))
+ .forEach(assetAndRules -> {
+ List<AssetRulesDefinition> rulesDefinitions = assetAndRules.value;
+ String[] assetRules = rulesStorageService.getRules(rulesDefinitions, AssetRulesDefinition.class);
+
+ if (assetRules.length != rulesDefinitions.size()) {
+ LOG.warning("Failed to retrieve asset rules definitions");
+ } else {
+ IntStream
+ .range(0, assetRules.length)
+ .forEach(i -> deployAssetRulesDefinition(rulesDefinitions.get(i), assetRules[i]));
+ }
+ });
+ });
+ }
+
protected void deployAssetRulesDefinition(AssetRulesDefinition rulesDefinition, String rules) {
// Look for existing deployment for this asset
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java
index 824c6a0f0..aff40056f 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java
@@ -160,6 +160,21 @@ public class RulesStorageService implements ContainerService {
);
}
+ public List<AssetRulesDefinition> findAllEnabledAssetDefinitions(String realmId) {
+ return persistenceService.doReturningTransaction(entityManager ->
+ entityManager.createQuery(
+ "select new org.openremote.manager.shared.rules.AssetRulesDefinition(" +
+ "rd.id, rd.version, rd.createdOn, rd.lastModified, rd.name, rd.enabled, rd.assetId" +
+ ") " +
+ "from AssetRulesDefinition rd, Asset a " +
+ "where rd.assetId = a.id and a.realmId = :realmId " +
+ "and rd.enabled = TRUE " +
+ "order by rd.createdOn asc",
+ AssetRulesDefinition.class
+ ).setParameter("realmId", realmId).getResultList()
+ );
+ }
+
// TODO: Update this as order is not guaranteed
protected <T extends RulesDefinition> String[] getRules(List<T> rulesDefinitions, Class<T> clazz) {
if (rulesDefinitions == null || rulesDefinitions.size() == 0) {
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 438284119..0ee22f99f 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
@@ -19,6 +19,7 @@
*/
package org.openremote.manager.server.security;
+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.RealmsResource;
@@ -27,6 +28,8 @@ import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.openremote.container.Container;
+import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.IdentityService;
import org.openremote.container.security.KeycloakResource;
@@ -50,6 +53,7 @@ public class ManagerIdentityService extends IdentityService {
protected boolean devMode;
protected PersistenceService persistenceService;
+ protected MessageBrokerService messageBrokerService;
public ManagerIdentityService() {
super(Constants.KEYCLOAK_CLIENT_ID);
@@ -61,6 +65,7 @@ public class ManagerIdentityService extends IdentityService {
this.devMode = container.isDevMode();
this.persistenceService = container.getService(PersistenceService.class);
+ this.messageBrokerService = container.getService(MessageBrokerService.class);
enableAuthProxy(container.getService(WebService.class));
@@ -189,6 +194,7 @@ public class ManagerIdentityService extends IdentityService {
getRealms(bearerAuth).create(realmRepresentation);
// TODO This is not atomic, write compensation actions
createClientApplication(bearerAuth, realmRepresentation.getRealm());
+ sendTenantModifiedMessage(PersistenceEvent.Cause.INSERT, tenant);
}
public void createClientApplication(String bearerAuth, String realm) {
@@ -207,11 +213,14 @@ public class ManagerIdentityService extends IdentityService {
getRealms(bearerAuth).realm(realm).update(
convert(Container.JSON, RealmRepresentation.class, tenant)
);
+ sendTenantModifiedMessage(PersistenceEvent.Cause.UPDATE, tenant);
}
public void deleteTenant(String bearerAuth, String realm) throws Exception {
+ Tenant tenant = getTenant(bearerAuth, realm);
LOG.fine("Delete tenant: " + realm);
getRealms(bearerAuth).realm(realm).remove();
+ sendTenantModifiedMessage(PersistenceEvent.Cause.DELETE, tenant);
}
public void addDefaultRoles(RolesResource rolesResource) {
@@ -258,6 +267,22 @@ public class ManagerIdentityService extends IdentityService {
return persistenceService.doReturningTransaction(em -> em.merge(userConfiguration));
}
+ /**
+ * Use PERSISTENCE_TOPIC and persistence event
+ * @param tenant
+ */
+ protected void sendTenantModifiedMessage(PersistenceEvent.Cause cause, Tenant tenant) {
+ PersistenceEvent persistenceEvent = new PersistenceEvent(cause, tenant, new String[0], null);
+
+ messageBrokerService.getProducerTemplate().sendBodyAndHeader(
+ PersistenceEvent.PERSISTENCE_TOPIC,
+ ExchangePattern.InOnly,
+ persistenceEvent,
+ PersistenceEvent.HEADER_ENTITY_TYPE,
+ persistenceEvent.getEntity().getClass()
+ );
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
index 21b3dbae6..c131059d9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
@@ -28,6 +28,7 @@ import org.openremote.container.Container;
import org.openremote.manager.server.setup.AbstractKeycloakSetup;
import org.openremote.manager.shared.security.ClientRole;
import org.openremote.manager.shared.security.Tenant;
+import org.openremote.model.Constants;
import java.util.*;
import java.util.logging.Logger;
@@ -48,6 +49,9 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {
public String testuser1Id;
public String testuser2Id;
public String testuser3Id;
+ public Tenant masterTenant;
+ public Tenant customerATenant;
+ public Tenant customerBTenant;
public KeycloakDemoSetup(Container container) {
super(container);
@@ -57,18 +61,21 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {
public void execute() throws Exception {
// Tenants
+ masterTenant = identityService.getTenant(accessToken, Constants.MASTER_REALM);
Tenant customerA = new Tenant();
customerA.setRealm("customerA");
customerA.setDisplayName("Customer A");
customerA.setEnabled(true);
identityService.createTenant(accessToken, customerA);
+ customerATenant = identityService.getTenant(accessToken, customerA.getRealm());
Tenant customerB = new Tenant();
customerB.setRealm("customerB");
customerB.setDisplayName("Customer B");
customerB.setEnabled(true);
identityService.createTenant(accessToken, customerB);
+ customerBTenant = identityService.getTenant(accessToken, customerB.getRealm());
// Users
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
index fe13e4273..bf3093255 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
@@ -4,13 +4,22 @@ import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.rules.RulesStorageService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
+import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.server.security.ManagerIdentityService
import org.openremote.manager.shared.rules.*
+import org.openremote.manager.shared.rules.RulesDefinition.DeploymentStatus
import org.openremote.model.Constants
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.IOUtils
+
+import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD
+import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT
+import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
+import static org.openremote.model.Constants.MASTER_REALM
+import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER;
class RulesDeploymentTest extends Specification implements ManagerContainerTrait {
@@ -19,17 +28,29 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
given: "expected conditions"
def conditions = new PollingConditions(timeout: 10, initialDelay: 1)
- when: "the demo assets and rule definitions have been deployed"
+ and: "the demo assets and rule definitions are deployed"
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
def rulesService = container.getService(RulesService.class)
def identityService = container.getService(ManagerIdentityService.class)
def rulesStorageService = container.getService(RulesStorageService.class)
def customerARealmId = identityService.getActiveTenantRealmId("customerA")
def customerBRealmId = identityService.getActiveTenantRealmId("customerB")
- then: "a global rules engine should have been created and be running"
+ and: "an authenticated user"
+ def authRealm = MASTER_REALM
+ def masterRealmId = getActiveTenantRealmId(container, MASTER_REALM)
+ def accessToken = authenticate(
+ container,
+ authRealm,
+ KEYCLOAK_CLIENT_ID,
+ MASTER_REALM_ADMIN_USER,
+ getString(container.getConfig(), SETUP_KEYCLOAK_ADMIN_PASSWORD, SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT)
+ ).token
+
+ expect: "a global rules engine should have been created and be running"
conditions.eventually {
assert rulesService.globalDeployment != null
assert rulesService.globalDeployment.isRunning()
@@ -40,6 +61,7 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert rulesService.globalDeployment.allRulesDefinitions.length == 1
assert rulesService.globalDeployment.allRulesDefinitions[0].enabled
assert rulesService.globalDeployment.allRulesDefinitions[0].name == "Some global demo rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
}
and: "two tenant rules engines should have been created and be running"
@@ -60,9 +82,11 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert masterEngine.allRulesDefinitions.length == 1
assert masterEngine.allRulesDefinitions[0].enabled
assert masterEngine.allRulesDefinitions[0].name == "Some master tenant demo rules"
+ assert masterEngine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
assert customerAEngine.allRulesDefinitions.length == 1
assert customerAEngine.allRulesDefinitions[0].enabled
assert customerAEngine.allRulesDefinitions[0].name == "Some customerA tenant demo rules"
+ assert customerAEngine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
}
and: "two asset rules engines should have been created and be running"
@@ -83,9 +107,11 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert apartment1Engine.allRulesDefinitions.length == 1
assert apartment1Engine.allRulesDefinitions[0].enabled
assert apartment1Engine.allRulesDefinitions[0].name == "Some apartment 1 demo rules"
+ assert apartment1Engine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
assert apartment3Engine.allRulesDefinitions.length == 1
assert apartment3Engine.allRulesDefinitions[0].enabled
assert apartment3Engine.allRulesDefinitions[0].name == "Some apartment 3 demo rules"
+ assert apartment3Engine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
}
when: "a new global rule definition is added"
@@ -101,8 +127,10 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert rulesService.globalDeployment.allRulesDefinitions.length == 2
assert rulesService.globalDeployment.allRulesDefinitions[0].enabled
assert rulesService.globalDeployment.allRulesDefinitions[0].name == "Some global demo rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
assert rulesService.globalDeployment.allRulesDefinitions[1].enabled
assert rulesService.globalDeployment.allRulesDefinitions[1].name == "Some more global rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[1].deploymentStatus == DeploymentStatus.DEPLOYED
}
when: "a new tenant rule definition is added to customer A"
@@ -119,8 +147,10 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert customerAEngine.allRulesDefinitions.length == 2
assert customerAEngine.allRulesDefinitions[0].enabled
assert customerAEngine.allRulesDefinitions[0].name == "Some customerA tenant demo rules"
+ assert customerAEngine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
assert customerAEngine.allRulesDefinitions[1].enabled
assert customerAEngine.allRulesDefinitions[1].name == "Some more customerA tenant rules"
+ assert customerAEngine.allRulesDefinitions[1].deploymentStatus == DeploymentStatus.DEPLOYED
}
when: "a new tenant rule definition is added to customer B"
@@ -137,12 +167,13 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert customerBEngine.allRulesDefinitions.length == 1
assert customerBEngine.allRulesDefinitions[0].enabled
assert customerBEngine.allRulesDefinitions[0].name == "Some more customerB tenant rules"
+ assert customerBEngine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
}
when: "the disabled rule definition for customer B is enabled"
rulesDefinition = rulesStorageService.findById(TenantRulesDefinition.class, managerDemoSetup.customerBRulesDefinitionId)
rulesDefinition.setEnabled(true)
- rulesStorageService.merge(rulesDefinition)
+ rulesDefinition = rulesStorageService.merge(rulesDefinition)
then: "customer B rule engine should load this definition and restart successfully"
conditions.eventually {
@@ -152,8 +183,25 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert customerBEngine.allRulesDefinitions.length == 2
assert customerBEngine.allRulesDefinitions[0].enabled
assert customerBEngine.allRulesDefinitions[0].name == "Some more customerB tenant rules"
+ assert customerBEngine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
assert customerBEngine.allRulesDefinitions[1].enabled
assert customerBEngine.allRulesDefinitions[1].name == "Some customerB tenant demo rules"
+ assert customerBEngine.allRulesDefinitions[1].deploymentStatus == DeploymentStatus.DEPLOYED
+ }
+
+ when: "the enabled rule definition for customer B is disabled"
+ rulesDefinition.setEnabled(false)
+ rulesStorageService.merge(rulesDefinition)
+
+ then: "customer B rule engine should should remove it again"
+ conditions.eventually {
+ def customerBEngine = rulesService.tenantDeployments.get(customerBRealmId)
+ assert customerBEngine != null
+ assert customerBEngine.isRunning()
+ assert customerBEngine.allRulesDefinitions.length == 1
+ assert customerBEngine.allRulesDefinitions[0].enabled
+ assert customerBEngine.allRulesDefinitions[0].name == "Some more customerB tenant rules"
+ assert customerBEngine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
}
when: "the rule definition for apartment 1 is deleted"
@@ -169,6 +217,75 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert apartment3Engine.isRunning()
}
+ when: "a broken rule definition is added to the global rules engine"
+ inputStream = getClass().getResourceAsStream("/org/openremote/test/rules/BrokenRules.drl")
+ rules = IOUtils.toString(inputStream, "UTF-8")
+ rulesDefinition = new GlobalRulesDefinition("Some broken global rules", rules)
+ rulesDefinition = rulesStorageService.merge(rulesDefinition)
+
+ then: "the global rules engine should not run and the rule deployment status status should indicate the issue"
+ conditions.eventually {
+ assert rulesService.globalDeployment.allRulesDefinitions.length == 3
+ assert rulesService.globalDeployment.running == false
+ assert rulesService.globalDeployment.error == true
+ assert rulesService.globalDeployment.allRulesDefinitions[0].enabled
+ assert rulesService.globalDeployment.allRulesDefinitions[0].name == "Some global demo rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.READY
+ assert rulesService.globalDeployment.allRulesDefinitions[1].enabled
+ assert rulesService.globalDeployment.allRulesDefinitions[1].name == "Some more global rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[1].deploymentStatus == DeploymentStatus.READY
+ assert rulesService.globalDeployment.allRulesDefinitions[2].enabled
+ assert rulesService.globalDeployment.allRulesDefinitions[2].name == "Some broken global rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[2].deploymentStatus == DeploymentStatus.FAILED
+ }
+
+ when: "the broken rule definition is removed from the global engine"
+ rulesStorageService.delete(GlobalRulesDefinition.class, rulesDefinition.getId())
+
+ then: "the global rules engine should restart"
+ conditions.eventually {
+ assert rulesService.globalDeployment.allRulesDefinitions.length == 2
+ assert rulesService.globalDeployment.running == true
+ assert rulesService.globalDeployment.error == false
+ assert rulesService.globalDeployment.allRulesDefinitions[0].enabled
+ assert rulesService.globalDeployment.allRulesDefinitions[0].name == "Some global demo rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert rulesService.globalDeployment.allRulesDefinitions[1].enabled
+ assert rulesService.globalDeployment.allRulesDefinitions[1].name == "Some more global rules"
+ assert rulesService.globalDeployment.allRulesDefinitions[1].deploymentStatus == DeploymentStatus.DEPLOYED
+ }
+
+ when: "a tenant is disabled"
+ def customerAEngine = rulesService.tenantDeployments.get(customerARealmId)
+ def customerATenant = keycloakDemoSetup.customerATenant
+ customerATenant.setEnabled(false)
+ identityService.updateTenant(accessToken, customerATenant.getRealm(), customerATenant)
+
+ then: "the tenants rule engine should stop and all asset rule engines from this realm should also stop"
+ conditions.eventually {
+ assert customerAEngine.isRunning() == false
+ assert customerAEngine.allRulesDefinitions.length == 0
+ assert rulesService.tenantDeployments.get(customerARealmId) == null
+ }
+
+ when: "a tenant is enabled"
+ customerATenant.setEnabled(true)
+ identityService.updateTenant(accessToken, customerATenant.getRealm(), customerATenant)
+
+ then: "the tenants rule engine should start and all asset rule engines from this realm should also start"
+ conditions.eventually {
+ customerAEngine = rulesService.tenantDeployments.get(customerARealmId)
+ assert customerAEngine != null
+ assert customerAEngine.isRunning()
+ assert customerAEngine.allRulesDefinitions.length == 2
+ assert customerAEngine.allRulesDefinitions[0].enabled
+ assert customerAEngine.allRulesDefinitions[0].name == "Some customerA tenant demo rules"
+ assert customerAEngine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert customerAEngine.allRulesDefinitions[1].enabled
+ assert customerAEngine.allRulesDefinitions[1].name == "Some more customerA tenant rules"
+ assert customerAEngine.allRulesDefinitions[1].deploymentStatus == DeploymentStatus.DEPLOYED
+ }
+
cleanup: "the server should be stopped"
stopContainer(container)
}
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RulesPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RulesPermissionsTest.groovy
index 29d3333ea..2bed3d5c9 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/RulesPermissionsTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RulesPermissionsTest.groovy
@@ -64,7 +64,7 @@ class RulesPermissionsTest extends Specification implements ManagerContainerTrai
then: "result should match"
ruleDefinitions.length == 1
ruleDefinitions[0].name == "Some customerA tenant demo rules"
- !ruleDefinitions[0].enabled
+ ruleDefinitions[0].enabled
when: "some asset rules are retrieved"
ruleDefinitions = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment1Id)
diff --git a/manager/test/src/test/resources/org/openremote/test/rules/BrokenRules.drl b/manager/test/src/test/resources/org/openremote/test/rules/BrokenRules.drl
new file mode 100644
index 000000000..3a387081f
--- /dev/null
+++ b/manager/test/src/test/resources/org/openremote/test/rules/BrokenRules.drl
@@ -0,0 +1,12 @@
+package org.openremote.test.rules;
+
+import org.openremote.agent.sensor.*
+
+global org.openremote.agent.rules.SwitchFacade switches;
+
+rule "Modify Switch State 2
+when
+ $switch : SwitchSensorState(sensorID == 123)
+then
+ switches.name($switch.getSensorName()).off();
+end