Search in sources :

Example 1 with GeofenceAssetAdapter

use of org.openremote.manager.rules.geofence.GeofenceAssetAdapter in project openremote by openremote.

the class RulesService method start.

@Override
public void start(Container container) throws Exception {
    if (!geofenceAssetAdapters.isEmpty()) {
        LOG.info("GeoefenceAssetAdapters found: " + geofenceAssetAdapters.size());
        locationPredicateRulesConsumer = this::onEngineLocationRulesChanged;
        for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
            geofenceAssetAdapter.start(container);
        }
    }
    LOG.info("Deploying global rulesets");
    rulesetStorageService.findAll(GlobalRuleset.class, new RulesetQuery().setEnabledOnly(true).setFullyPopulate(true)).forEach(this::deployGlobalRuleset);
    LOG.info("Deploying tenant rulesets");
    tenants = Arrays.stream(identityService.getIdentityProvider().getTenants()).filter(Tenant::getEnabled).toArray(Tenant[]::new);
    rulesetStorageService.findAll(TenantRuleset.class, new RulesetQuery().setEnabledOnly(true).setFullyPopulate(true)).stream().filter(rd -> Arrays.stream(tenants).anyMatch(tenant -> rd.getRealm().equals(tenant.getRealm()))).forEach(this::deployTenantRuleset);
    LOG.info("Deploying asset rulesets");
    // Group by asset ID then tenant and check tenant is enabled
    // noinspection ResultOfMethodCallIgnored
    deployAssetRulesets(rulesetStorageService.findAll(AssetRuleset.class, new RulesetQuery().setEnabledOnly(true).setFullyPopulate(true))).count();
    LOG.info("Loading all assets with fact attributes to initialize state of rules engines");
    Stream<Pair<Asset<?>, Stream<Attribute<?>>>> stateAttributes = findRuleStateAttributes();
    // Push each attribute as an asset update through the rule engine chain
    // that will ensure the insert only happens to the engines in scope
    stateAttributes.forEach(pair -> {
        Asset<?> asset = pair.key;
        pair.value.forEach(ruleAttribute -> {
            AssetState<?> assetState = new AssetState<>(asset, ruleAttribute, Source.INTERNAL);
            updateAssetState(assetState);
        });
    });
    // Start the engines
    if (globalEngine != null) {
        globalEngine.start();
    }
    tenantEngines.values().forEach(RulesEngine::start);
    assetEngines.values().forEach(RulesEngine::start);
    startDone = true;
    preInitassetStates.forEach(this::doProcessAssetUpdate);
    preInitassetStates.clear();
}
Also used : ClientRole(org.openremote.model.security.ClientRole) BiFunction(java.util.function.BiFunction) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) ValueUtil(org.openremote.model.util.ValueUtil) MapAccess.getString(org.openremote.container.util.MapAccess.getString) GeofenceAssetAdapter(org.openremote.manager.rules.geofence.GeofenceAssetAdapter) Attribute.getAddedOrModifiedAttributes(org.openremote.model.attribute.Attribute.getAddedOrModifiedAttributes) org.openremote.model.rules(org.openremote.model.rules) AssetPredictedDatapointService(org.openremote.manager.datapoint.AssetPredictedDatapointService) GeofenceDefinition(org.openremote.model.rules.geofence.GeofenceDefinition) ContainerService(org.openremote.model.ContainerService) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) Stream(java.util.stream.Stream) RouteBuilder(org.apache.camel.builder.RouteBuilder) PERSISTENCE_TOPIC(org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC) RulesetQuery(org.openremote.model.query.RulesetQuery) GatewayService(org.openremote.manager.gateway.GatewayService) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) AssetStorageService(org.openremote.manager.asset.AssetStorageService) Tenant(org.openremote.model.security.Tenant) AttributeMap(org.openremote.model.attribute.AttributeMap) GatewayService.isNotForGateway(org.openremote.manager.gateway.GatewayService.isNotForGateway) java.util(java.util) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) NotificationService(org.openremote.manager.notification.NotificationService) SEVERE(java.util.logging.Level.SEVERE) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) LocationAttributePredicate(org.openremote.model.query.filter.LocationAttributePredicate) Attribute(org.openremote.model.attribute.Attribute) PersistenceService(org.openremote.container.persistence.PersistenceService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ManagerWebService(org.openremote.manager.web.ManagerWebService) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) FlowResourceImpl(org.openremote.manager.rules.flow.FlowResourceImpl) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) MetaItemType(org.openremote.model.value.MetaItemType) AssetQuery(org.openremote.model.query.AssetQuery) Pair(org.openremote.model.util.Pair) EntityManager(javax.persistence.EntityManager) ClientEventService(org.openremote.manager.event.ClientEventService) Collectors.toList(java.util.stream.Collectors.toList) TimerService(org.openremote.container.timer.TimerService) AssetUpdateProcessor(org.openremote.manager.asset.AssetUpdateProcessor) PersistenceService.isPersistenceEventForEntityType(org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType) Source(org.openremote.model.attribute.AttributeEvent.Source) FINEST(java.util.logging.Level.FINEST) RulesetQuery(org.openremote.model.query.RulesetQuery) Attribute(org.openremote.model.attribute.Attribute) GeofenceAssetAdapter(org.openremote.manager.rules.geofence.GeofenceAssetAdapter) Tenant(org.openremote.model.security.Tenant) Pair(org.openremote.model.util.Pair)

Example 2 with GeofenceAssetAdapter

use of org.openremote.manager.rules.geofence.GeofenceAssetAdapter in project openremote by openremote.

the class RulesService method processModifiedGeofences.

protected void processModifiedGeofences() {
    withLock(getClass().getSimpleName() + "::processModifiedGeofences", () -> {
        LOG.finest("Processing geofence modifications: modified asset geofence count=" + assetsWithModifiedLocationPredicates.size());
        try {
            // Find all location predicates associated with modified assets and pass through to the geofence adapters
            List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates = new ArrayList<>(assetsWithModifiedLocationPredicates.size());
            assetsWithModifiedLocationPredicates.forEach(assetId -> {
                RulesEngine.AssetStateLocationPredicates locationPredicates = new RulesEngine.AssetStateLocationPredicates(assetId, new HashSet<>());
                engineAssetLocationPredicateMap.forEach((rulesEngine, engineAssetStateLocationPredicates) -> engineAssetStateLocationPredicates.stream().filter(assetStateLocationPredicates -> assetStateLocationPredicates.getAssetId().equals(assetId)).findFirst().ifPresent(assetStateLocationPredicate -> {
                    locationPredicates.getLocationPredicates().addAll(assetStateLocationPredicate.getLocationPredicates());
                }));
                assetLocationPredicates.add(locationPredicates);
            });
            for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
                LOG.finest("Passing modified geofences to adapter: " + geofenceAssetAdapter.getName());
                geofenceAssetAdapter.processLocationPredicates(assetLocationPredicates);
                if (assetLocationPredicates.isEmpty()) {
                    LOG.finest("All modified geofences handled");
                    break;
                }
            }
        } catch (Exception e) {
            LOG.log(SEVERE, "Exception thrown by geofence adapter whilst processing location predicates", e);
        } finally {
            // Clear modified assets ready for next batch
            assetsWithModifiedLocationPredicates.clear();
        }
    });
}
Also used : ClientRole(org.openremote.model.security.ClientRole) BiFunction(java.util.function.BiFunction) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) ValueUtil(org.openremote.model.util.ValueUtil) MapAccess.getString(org.openremote.container.util.MapAccess.getString) GeofenceAssetAdapter(org.openremote.manager.rules.geofence.GeofenceAssetAdapter) Attribute.getAddedOrModifiedAttributes(org.openremote.model.attribute.Attribute.getAddedOrModifiedAttributes) org.openremote.model.rules(org.openremote.model.rules) AssetPredictedDatapointService(org.openremote.manager.datapoint.AssetPredictedDatapointService) GeofenceDefinition(org.openremote.model.rules.geofence.GeofenceDefinition) ContainerService(org.openremote.model.ContainerService) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) Stream(java.util.stream.Stream) RouteBuilder(org.apache.camel.builder.RouteBuilder) PERSISTENCE_TOPIC(org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC) RulesetQuery(org.openremote.model.query.RulesetQuery) GatewayService(org.openremote.manager.gateway.GatewayService) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) AssetStorageService(org.openremote.manager.asset.AssetStorageService) Tenant(org.openremote.model.security.Tenant) AttributeMap(org.openremote.model.attribute.AttributeMap) GatewayService.isNotForGateway(org.openremote.manager.gateway.GatewayService.isNotForGateway) java.util(java.util) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) NotificationService(org.openremote.manager.notification.NotificationService) SEVERE(java.util.logging.Level.SEVERE) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) LocationAttributePredicate(org.openremote.model.query.filter.LocationAttributePredicate) Attribute(org.openremote.model.attribute.Attribute) PersistenceService(org.openremote.container.persistence.PersistenceService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ManagerWebService(org.openremote.manager.web.ManagerWebService) PersistenceEvent(org.openremote.model.PersistenceEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService) FlowResourceImpl(org.openremote.manager.rules.flow.FlowResourceImpl) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) MetaItemType(org.openremote.model.value.MetaItemType) AssetQuery(org.openremote.model.query.AssetQuery) Pair(org.openremote.model.util.Pair) EntityManager(javax.persistence.EntityManager) ClientEventService(org.openremote.manager.event.ClientEventService) Collectors.toList(java.util.stream.Collectors.toList) TimerService(org.openremote.container.timer.TimerService) AssetUpdateProcessor(org.openremote.manager.asset.AssetUpdateProcessor) PersistenceService.isPersistenceEventForEntityType(org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType) Source(org.openremote.model.attribute.AttributeEvent.Source) FINEST(java.util.logging.Level.FINEST) GeofenceAssetAdapter(org.openremote.manager.rules.geofence.GeofenceAssetAdapter) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException)

Example 3 with GeofenceAssetAdapter

use of org.openremote.manager.rules.geofence.GeofenceAssetAdapter in project openremote by openremote.

the class RulesService method stop.

@Override
public void stop(Container container) throws Exception {
    withLock(getClass().getSimpleName() + "::stop", () -> {
        for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
            try {
                geofenceAssetAdapter.stop(container);
            } catch (Exception e) {
                LOG.log(SEVERE, "Exception thrown whilst stopping geofence adapter", e);
            }
        }
        assetEngines.forEach((assetId, rulesEngine) -> rulesEngine.stop(true));
        assetEngines.clear();
        tenantEngines.forEach((realm, rulesEngine) -> rulesEngine.stop(true));
        tenantEngines.clear();
        if (globalEngine != null) {
            globalEngine.stop(true);
            globalEngine = null;
        }
        assetStates.clear();
    });
    for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {
        geofenceAssetAdapter.stop(container);
    }
}
Also used : GeofenceAssetAdapter(org.openremote.manager.rules.geofence.GeofenceAssetAdapter) AssetProcessingException(org.openremote.manager.asset.AssetProcessingException)

Example 4 with GeofenceAssetAdapter

use of org.openremote.manager.rules.geofence.GeofenceAssetAdapter in project openremote by openremote.

the class RulesService method init.

@Override
public void init(Container container) throws Exception {
    executorService = container.getExecutorService();
    timerService = container.getService(TimerService.class);
    persistenceService = container.getService(PersistenceService.class);
    rulesetStorageService = container.getService(RulesetStorageService.class);
    identityService = container.getService(ManagerIdentityService.class);
    notificationService = container.getService(NotificationService.class);
    assetStorageService = container.getService(AssetStorageService.class);
    assetProcessingService = container.getService(AssetProcessingService.class);
    assetDatapointService = container.getService(AssetDatapointService.class);
    assetPredictedDatapointService = container.getService(AssetPredictedDatapointService.class);
    clientEventService = container.getService(ClientEventService.class);
    gatewayService = container.getService(GatewayService.class);
    if (initDone) {
        return;
    }
    clientEventService.addSubscriptionAuthorizer((realm, auth, subscription) -> {
        if (subscription.isEventType(RulesEngineStatusEvent.class) || subscription.isEventType(RulesetChangedEvent.class)) {
            if (auth == null) {
                return false;
            }
            if (auth.isSuperUser()) {
                return true;
            }
            // Regular user must have role
            if (!auth.hasResourceRole(ClientRole.READ_ASSETS.getValue(), auth.getClientId())) {
                return false;
            }
            boolean isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(auth);
            return !isRestrictedUser;
        }
        return false;
    });
    ServiceLoader.load(GeofenceAssetAdapter.class).forEach(geofenceAssetAdapter -> {
        LOG.fine("Adding GeofenceAssetAdapter: " + geofenceAssetAdapter.getClass().getName());
        geofenceAssetAdapters.add(geofenceAssetAdapter);
    });
    geofenceAssetAdapters.addAll(container.getServices(GeofenceAssetAdapter.class));
    geofenceAssetAdapters.sort(Comparator.comparingInt(GeofenceAssetAdapter::getPriority));
    container.getService(MessageBrokerService.class).getContext().addRoutes(this);
    configEventExpires = getString(container.getConfig(), RULE_EVENT_EXPIRES, RULE_EVENT_EXPIRES_DEFAULT);
    container.getService(ManagerWebService.class).addApiSingleton(new FlowResourceImpl(container.getService(TimerService.class), container.getService(ManagerIdentityService.class)));
    initDone = true;
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) AssetPredictedDatapointService(org.openremote.manager.datapoint.AssetPredictedDatapointService) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) GeofenceAssetAdapter(org.openremote.manager.rules.geofence.GeofenceAssetAdapter) NotificationService(org.openremote.manager.notification.NotificationService) TimerService(org.openremote.container.timer.TimerService) GatewayService(org.openremote.manager.gateway.GatewayService) PersistenceService(org.openremote.container.persistence.PersistenceService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) ManagerWebService(org.openremote.manager.web.ManagerWebService) ClientEventService(org.openremote.manager.event.ClientEventService) FlowResourceImpl(org.openremote.manager.rules.flow.FlowResourceImpl)

Aggregations

GeofenceAssetAdapter (org.openremote.manager.rules.geofence.GeofenceAssetAdapter)4 PersistenceService (org.openremote.container.persistence.PersistenceService)3 TimerService (org.openremote.container.timer.TimerService)3 AssetProcessingException (org.openremote.manager.asset.AssetProcessingException)3 AssetProcessingService (org.openremote.manager.asset.AssetProcessingService)3 AssetStorageService (org.openremote.manager.asset.AssetStorageService)3 AssetDatapointService (org.openremote.manager.datapoint.AssetDatapointService)3 AssetPredictedDatapointService (org.openremote.manager.datapoint.AssetPredictedDatapointService)3 ClientEventService (org.openremote.manager.event.ClientEventService)3 GatewayService (org.openremote.manager.gateway.GatewayService)3 NotificationService (org.openremote.manager.notification.NotificationService)3 FlowResourceImpl (org.openremote.manager.rules.flow.FlowResourceImpl)3 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)3 ManagerWebService (org.openremote.manager.web.ManagerWebService)3 java.util (java.util)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 BiFunction (java.util.function.BiFunction)2 FINEST (java.util.logging.Level.FINEST)2 SEVERE (java.util.logging.Level.SEVERE)2 Logger (java.util.logging.Logger)2