summaryrefslogtreecommitdiffstats
path: root/services/services-engine/src
diff options
context:
space:
mode:
authora.sreekumar <ajith.sreekumar@est.tech>2019-10-16 11:46:21 +0100
committerAjith Sreekumar <ajith.sreekumar@est.tech>2019-11-01 08:49:37 +0000
commit82da1e9fa73e6a19455ea979bbf084aeed43af90 (patch)
tree88efd6fe5317262d894f8945c39ec431748bfca8 /services/services-engine/src
parentc03a0455e2956e43e425d6f4121ab5d8d20158f1 (diff)
Resolve mapping between TOSCA policies and APEX policy models
Change-Id: Ifaedc5074bcc51a5d495e342feae89b6a2aac1cf Issue-ID: POLICY-1626 Signed-off-by: a.sreekumar <ajith.sreekumar@est.tech>
Diffstat (limited to 'services/services-engine/src')
-rw-r--r--services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexActivator.java191
-rw-r--r--services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java125
-rw-r--r--services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java44
-rw-r--r--services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java22
-rw-r--r--services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java87
5 files changed, 329 insertions, 140 deletions
diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexActivator.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexActivator.java
index 3aa1f17ff..2c3fac151 100644
--- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexActivator.java
+++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexActivator.java
@@ -24,17 +24,24 @@ package org.onap.policy.apex.service.engine.main;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
-
+import java.util.stream.Stream;
+import lombok.Getter;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
+import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
+import org.onap.policy.apex.model.policymodel.handling.PolicyModelMerger;
import org.onap.policy.apex.model.utilities.TextFileUtils;
import org.onap.policy.apex.service.engine.engdep.EngDepMessagingService;
+import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.apex.service.engine.runtime.EngineService;
import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl;
import org.onap.policy.apex.service.parameters.ApexParameters;
+import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
import org.onap.policy.common.parameters.ParameterService;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
@@ -45,11 +52,14 @@ import org.slf4j.ext.XLoggerFactory;
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class ApexActivator {
+ private static final String APEX_ENGINE_FAILED_MSG = "Apex engine failed to start as a service";
+
// The logger for this class
private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexActivator.class);
- // The parameters of this Apex activator
- private final ApexParameters apexParameters;
+ // The parameters of the Apex activator when running with multiple policies
+ @Getter
+ private Map<ToscaPolicyIdentifier, ApexParameters> apexParametersMap;
// Event unmarshalers are used to receive events asynchronously into Apex
private final Map<String, ApexEventUnmarshaller> unmarshallerMap = new LinkedHashMap<>();
@@ -62,13 +72,16 @@ public class ApexActivator {
// and synchronous events from the engine.
private ApexEngineServiceHandler engineServiceHandler = null;
+ // The engine service
+ private EngineService apexEngineService;
+
/**
* Instantiate the activator for the Apex engine as a complete service.
*
- * @param parameters the apex parameters for the Apex service
+ * @param parametersMap the apex parameters map for the Apex service
*/
- public ApexActivator(final ApexParameters parameters) {
- apexParameters = parameters;
+ public ApexActivator(Map<ToscaPolicyIdentifier, ApexParameters> parametersMap) {
+ apexParametersMap = parametersMap;
}
/**
@@ -80,61 +93,118 @@ public class ApexActivator {
LOGGER.debug("Apex engine starting as a service . . .");
try {
- // Create engine with specified thread count
- LOGGER.debug("starting apex engine service . . .");
- final EngineService apexEngineService =
- EngineServiceImpl.create(apexParameters.getEngineServiceParameters());
-
- // Instantiate and start the messaging service for Deployment
- LOGGER.debug("starting apex deployment service . . .");
- final EngDepMessagingService engDepService = new EngDepMessagingService(apexEngineService,
- apexParameters.getEngineServiceParameters().getDeploymentPort());
- engDepService.start();
-
- // Create the engine holder to hold the engine's references and act as an event receiver
- engineServiceHandler = new ApexEngineServiceHandler(apexEngineService, engDepService);
-
- // Check if a policy model file has been specified
- if (apexParameters.getEngineServiceParameters().getPolicyModelFileName() != null) {
- LOGGER.debug("deploying policy model in \""
- + apexParameters.getEngineServiceParameters().getPolicyModelFileName()
+ ApexParameters apexParameters = apexParametersMap.values().iterator().next();
+ // totalInstanceCount is the sum of instance counts required as per each policy
+ int totalInstanceCount = apexParametersMap.values().stream()
+ .mapToInt(p -> p.getEngineServiceParameters().getInstanceCount()).sum();
+ apexParameters.getEngineServiceParameters().setInstanceCount(totalInstanceCount);
+ instantiateEngine(apexParameters);
+ Map<ToscaPolicyIdentifier, AxPolicyModel> policyModelsMap = new LinkedHashMap<>();
+ Map<String, EventHandlerParameters> inputParametersMap = new LinkedHashMap<>();
+ Map<String, EventHandlerParameters> outputParametersMap = new LinkedHashMap<>();
+
+ for (Entry<ToscaPolicyIdentifier, ApexParameters> apexParamsEntry : apexParametersMap.entrySet()) {
+ ApexParameters apexParams = apexParamsEntry.getValue();
+ boolean duplicateInputParameterExist =
+ apexParams.getEventInputParameters().keySet().stream().anyMatch(inputParametersMap::containsKey);
+ boolean duplicateOutputParameterExist =
+ apexParams.getEventOutputParameters().keySet().stream().anyMatch(outputParametersMap::containsKey);
+ if (duplicateInputParameterExist || duplicateOutputParameterExist) {
+ LOGGER.error("I/O Parameters for " + apexParamsEntry.getKey().getName() + ":"
+ + apexParamsEntry.getKey().getVersion()
+ + " has duplicates. So this policy is not executed");
+ apexParametersMap.remove(apexParamsEntry.getKey());
+ continue;
+ } else {
+ inputParametersMap.putAll(apexParams.getEventInputParameters());
+ outputParametersMap.putAll(apexParams.getEventOutputParameters());
+ }
+ // Check if a policy model file has been specified
+ if (apexParams.getEngineServiceParameters().getPolicyModelFileName() != null) {
+ LOGGER.debug("deploying policy model in \""
+ + apexParams.getEngineServiceParameters().getPolicyModelFileName()
+ "\" to the apex engines . . .");
- // Set the policy model in the engine
- final String policyModelString = TextFileUtils
- .getTextFileAsString(apexParameters.getEngineServiceParameters().getPolicyModelFileName());
- apexEngineService.updateModel(apexParameters.getEngineServiceParameters().getEngineKey(),
- policyModelString, true);
+ final String policyModelString = TextFileUtils
+ .getTextFileAsString(apexParams.getEngineServiceParameters().getPolicyModelFileName());
+ AxPolicyModel policyModel = EngineServiceImpl
+ .createModel(apexParams.getEngineServiceParameters().getEngineKey(), policyModelString);
+ policyModelsMap.put(apexParamsEntry.getKey(), policyModel);
+ }
}
+ AxPolicyModel finalPolicyModel = aggregatePolicyModels(policyModelsMap);
+ // Set the policy model in the engine
+ apexEngineService.updateModel(apexParameters.getEngineServiceParameters().getEngineKey(),
+ finalPolicyModel, true);
+ setUpMarshallerAndUnmarshaller(apexParameters.getEngineServiceParameters(), inputParametersMap,
+ outputParametersMap);
+ setUpmarshalerPairings(inputParametersMap);
+ } catch (final Exception e) {
+ LOGGER.debug(APEX_ENGINE_FAILED_MSG, e);
+ throw new ApexActivatorException(APEX_ENGINE_FAILED_MSG, e);
+ }
- // Producer parameters specify what event marshalers to handle events leaving Apex are
- // set up and how they are set up
- for (final Entry<String, EventHandlerParameters> outputParameters : apexParameters
- .getEventOutputParameters().entrySet()) {
- final ApexEventMarshaller marshaller = new ApexEventMarshaller(outputParameters.getKey(),
- apexParameters.getEngineServiceParameters(), outputParameters.getValue());
- marshaller.init();
- apexEngineService.registerActionListener(outputParameters.getKey(), marshaller);
- marshallerMap.put(outputParameters.getKey(), marshaller);
- }
+ LOGGER.debug("Apex engine started as a service");
+ }
- // Consumer parameters specify what event unmarshalers to handle events coming into Apex
- // are set up and how they are set up
- for (final Entry<String, EventHandlerParameters> inputParameters : apexParameters.getEventInputParameters()
- .entrySet()) {
- final ApexEventUnmarshaller unmarshaller = new ApexEventUnmarshaller(inputParameters.getKey(),
- apexParameters.getEngineServiceParameters(), inputParameters.getValue());
- unmarshallerMap.put(inputParameters.getKey(), unmarshaller);
- unmarshaller.init(engineServiceHandler);
- }
+ private AxPolicyModel aggregatePolicyModels(Map<ToscaPolicyIdentifier, AxPolicyModel> policyModelsMap) {
+ Map.Entry<ToscaPolicyIdentifier, AxPolicyModel> firstEntry = policyModelsMap.entrySet().iterator().next();
+ Stream<Entry<ToscaPolicyIdentifier, AxPolicyModel>> policyModelStream =
+ policyModelsMap.entrySet().stream().skip(1);
+ Entry<ToscaPolicyIdentifier, AxPolicyModel> finalPolicyModelEntry =
+ policyModelStream.reduce(firstEntry, ((entry1, entry2) -> {
+ try {
+ entry1.setValue(
+ PolicyModelMerger.getMergedPolicyModel(entry1.getValue(), entry2.getValue(), true, true));
+ } catch (ApexModelException exc) {
+ LOGGER.error("Policy model for " + entry2.getKey().getName() + ":" + entry2.getKey().getVersion()
+ + " is having duplicates. So this policy is not executed", exc.getMessage());
+ apexParametersMap.remove(entry2.getKey());
+ }
+ return entry1;
+ }));
+ return finalPolicyModelEntry.getValue();
+ }
- setUpmarshalerPairings();
- } catch (final Exception e) {
- LOGGER.debug("Apex engine failed to start as a service", e);
- throw new ApexActivatorException("Apex engine failed to start as a service", e);
+ private void setUpMarshallerAndUnmarshaller(EngineServiceParameters engineServiceParameters,
+ Map<String, EventHandlerParameters> inputParametersMap, Map<String, EventHandlerParameters> outputParametersMap)
+ throws ApexEventException {
+ // Producer parameters specify what event marshalers to handle events leaving Apex are
+ // set up and how they are set up
+ for (Entry<String, EventHandlerParameters> outputParameters : outputParametersMap.entrySet()) {
+ final ApexEventMarshaller marshaller = new ApexEventMarshaller(outputParameters.getKey(),
+ engineServiceParameters, outputParameters.getValue());
+ marshaller.init();
+ apexEngineService.registerActionListener(outputParameters.getKey(), marshaller);
+ marshallerMap.put(outputParameters.getKey(), marshaller);
}
+ // Consumer parameters specify what event unmarshalers to handle events coming into Apex
+ // are set up and how they are set up
+ for (final Entry<String, EventHandlerParameters> inputParameters : inputParametersMap.entrySet()) {
+ final ApexEventUnmarshaller unmarshaller = new ApexEventUnmarshaller(inputParameters.getKey(),
+ engineServiceParameters, inputParameters.getValue());
+ unmarshallerMap.put(inputParameters.getKey(), unmarshaller);
+ unmarshaller.init(engineServiceHandler);
+ }
+ }
- LOGGER.debug("Apex engine started as a service");
+ private void instantiateEngine(ApexParameters apexParameters) throws ApexException {
+ if (null != apexEngineService
+ && apexEngineService.getKey().equals(apexParameters.getEngineServiceParameters().getEngineKey())) {
+ throw new ApexException("Apex Engine already initialized.");
+ }
+ // Create engine with specified thread count
+ LOGGER.debug("starting apex engine service . . .");
+ apexEngineService = EngineServiceImpl.create(apexParameters.getEngineServiceParameters());
+
+ // Instantiate and start the messaging service for Deployment
+ LOGGER.debug("starting apex deployment service . . .");
+ final EngDepMessagingService engDepService = new EngDepMessagingService(apexEngineService,
+ apexParameters.getEngineServiceParameters().getDeploymentPort());
+ engDepService.start();
+
+ // Create the engine holder to hold the engine's references and act as an event receiver
+ engineServiceHandler = new ApexEngineServiceHandler(apexEngineService, engDepService);
}
/**
@@ -143,10 +213,10 @@ public class ApexActivator {
* unmarshalers and marshalers are paired one to one uniquely so if we find a
* synchronized unmarshaler we'll also find its
* paired marshaler
+ * @param inputParametersMap the apex parameters
*/
- private void setUpmarshalerPairings() {
- for (final Entry<String, EventHandlerParameters> inputParameters : apexParameters.getEventInputParameters()
- .entrySet()) {
+ private void setUpmarshalerPairings(Map<String, EventHandlerParameters> inputParametersMap) {
+ for (final Entry<String, EventHandlerParameters> inputParameters : inputParametersMap.entrySet()) {
final ApexEventUnmarshaller unmarshaller = unmarshallerMap.get(inputParameters.getKey());
// Pair up peered unmarshalers and marshalers
@@ -193,13 +263,4 @@ public class ApexActivator {
ModelService.clear();
ParameterService.clear();
}
-
- /**
- * Get the parameters used by the adapter.
- *
- * @return the parameters of the adapter
- */
- public ApexParameters getApexParameters() {
- return apexParameters;
- }
}
diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java
index 3bf842c92..4600690e7 100644
--- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java
+++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java
@@ -23,6 +23,8 @@ package org.onap.policy.apex.service.engine.main;
import java.util.Arrays;
import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.Map;
import java.util.Map.Entry;
import lombok.Getter;
import lombok.Setter;
@@ -30,6 +32,7 @@ import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.service.parameters.ApexParameterHandler;
import org.onap.policy.apex.service.parameters.ApexParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
@@ -39,13 +42,16 @@ import org.slf4j.ext.XLoggerFactory;
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class ApexMain {
+ private static final String APEX_SERVICE_FAILED_MSG = "start of Apex service failed";
+
private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexMain.class);
// The Apex Activator that activates the Apex engine
private ApexActivator activator;
- // The parameters read in from JSON
- private ApexParameters parameters;
+ // The parameters read in from JSON for each policy
+ @Getter
+ private Map<ToscaPolicyIdentifier, ApexParameters> apexParametersMap;
@Getter
@Setter(lombok.AccessLevel.PRIVATE)
@@ -54,11 +60,75 @@ public class ApexMain {
/**
* Instantiates the Apex service.
*
- * @param args the commaind line arguments
+ * @param args the command line arguments
*/
public ApexMain(final String[] args) {
LOGGER.entry("Starting Apex service with parameters " + Arrays.toString(args) + " . . .");
+ apexParametersMap = new LinkedHashMap<>();
+ try {
+ apexParametersMap.put(new ToscaPolicyIdentifier(), populateApexParameters(args));
+ } catch (ApexException e) {
+ LOGGER.error(APEX_SERVICE_FAILED_MSG, e);
+ return;
+ }
+
+ // Now, create the activator for the Apex service
+ activator = new ApexActivator(apexParametersMap);
+
+ // Start the activator
+ try {
+ activator.initialize();
+ setAlive(true);
+ } catch (final ApexActivatorException e) {
+ LOGGER.error("start of Apex service failed, used parameters are " + Arrays.toString(args), e);
+ return;
+ }
+
+ // Add a shutdown hook to shut everything down in an orderly manner
+ Runtime.getRuntime().addShutdownHook(new ApexMainShutdownHookClass());
+ LOGGER.exit("Started Apex");
+ }
+ /**
+ * Instantiates the Apex service for multiple policies.
+ *
+ * @param policyArgumentsMap the map with command line arguments as value and policy-id as key
+ * @throws ApexException on errors
+ */
+ public ApexMain(Map<ToscaPolicyIdentifier, String[]> policyArgumentsMap) throws ApexException {
+ apexParametersMap = new LinkedHashMap<>();
+ for ( Entry<ToscaPolicyIdentifier, String[]> policyArgsEntry: policyArgumentsMap.entrySet()) {
+ try {
+ apexParametersMap.put(policyArgsEntry.getKey(), populateApexParameters(policyArgsEntry.getValue()));
+ } catch (ApexException e) {
+ LOGGER.error("Invalid arguments specified for policy - " + policyArgsEntry.getKey().getName() + ":"
+ + policyArgsEntry.getKey().getVersion(), e);
+ }
+ }
+ if (apexParametersMap.isEmpty()) {
+ LOGGER.error(APEX_SERVICE_FAILED_MSG);
+ return;
+ }
+ // Now, create the activator for the Apex service
+ activator = new ApexActivator(apexParametersMap);
+
+ // Start the activator
+ try {
+ activator.initialize();
+ apexParametersMap = activator.getApexParametersMap();
+ setAlive(true);
+ } catch (final ApexActivatorException e) {
+ LOGGER.error(APEX_SERVICE_FAILED_MSG, e);
+ activator.terminate();
+ return;
+ }
+
+ // Add a shutdown hook to shut everything down in an orderly manner
+ Runtime.getRuntime().addShutdownHook(new ApexMainShutdownHookClass());
+ LOGGER.exit("Started Apex");
+ }
+
+ private ApexParameters populateApexParameters(String[] args) throws ApexException {
// Check the arguments
final ApexCommandLineArguments arguments = new ApexCommandLineArguments();
try {
@@ -66,65 +136,46 @@ public class ApexMain {
final String argumentMessage = arguments.parse(args);
if (argumentMessage != null) {
LOGGER.info(argumentMessage);
- return;
+ throw new ApexException(argumentMessage);
}
// Validate that the arguments are sane
arguments.validate();
} catch (final ApexException e) {
- LOGGER.error("start of Apex service failed", e);
- return;
+ LOGGER.error("Arguments validation failed.", e);
+ throw new ApexException("Arguments validation failed.", e);
}
+ ApexParameters axParameters;
// Read the parameters
try {
- parameters = new ApexParameterHandler().getParameters(arguments);
+ ApexParameterHandler apexParameterHandler = new ApexParameterHandler();
+ // In case of multiple policies received from PAP, do not clear ParameterService if parameters of one policy
+ // already registered
+ apexParameterHandler.setKeepParameterServiceFlag(null != apexParametersMap && !apexParametersMap.isEmpty());
+ axParameters = apexParameterHandler.getParameters(arguments);
} catch (final Exception e) {
- LOGGER.error("start of Apex service failed", e);
- return;
+ LOGGER.error("Cannot create APEX Parameters from the arguments provided.", e);
+ throw new ApexException("Cannot create APEX Parameters from the arguments provided.", e);
}
// Set incoming Java properties
- setJavaProperties(parameters);
+ setJavaProperties(axParameters);
// Set the name of the event handler parameters for producers and consumers
- for (final Entry<String, EventHandlerParameters> ehParameterEntry : parameters.getEventOutputParameters()
+ for (final Entry<String, EventHandlerParameters> ehParameterEntry : axParameters.getEventOutputParameters()
.entrySet()) {
if (!ehParameterEntry.getValue().checkSetName()) {
ehParameterEntry.getValue().setName(ehParameterEntry.getKey());
}
}
- for (final Entry<String, EventHandlerParameters> ehParameterEntry : parameters.getEventInputParameters()
+ for (final Entry<String, EventHandlerParameters> ehParameterEntry : axParameters.getEventInputParameters()
.entrySet()) {
if (!ehParameterEntry.getValue().checkSetName()) {
ehParameterEntry.getValue().setName(ehParameterEntry.getKey());
}
}
-
- // Now, create the activator for the Apex service
- activator = new ApexActivator(parameters);
-
- // Start the activator
- try {
- activator.initialize();
- setAlive(true);
- } catch (final ApexActivatorException e) {
- LOGGER.error("start of Apex service failed, used parameters are " + Arrays.toString(args), e);
- return;
- }
-
- // Add a shutdown hook to shut everything down in an orderly manner
- Runtime.getRuntime().addShutdownHook(new ApexMainShutdownHookClass());
- LOGGER.exit("Started Apex");
- }
-
- /**
- * Get the parameters specified in JSON.
- *
- * @return the parameters
- */
- public ApexParameters getParameters() {
- return parameters;
+ return axParameters;
}
/**
diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java
index e9edd40e2..152425711 100644
--- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java
+++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java
@@ -1,19 +1,20 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
@@ -28,7 +29,6 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
-
import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
@@ -134,13 +134,13 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven
LOGGER.warn("Engine service configuration parameters is null");
throw new ApexException("engine service configuration parameters are null");
}
-
+
final GroupValidationResult validation = config.validate();
if (!validation.isValid()) {
LOGGER.warn("Invalid engine service configuration parameters: {}" + validation.getResult());
throw new ApexException("Invalid engine service configuration parameters: " + validation);
}
-
+
final AxArtifactKey engineServiceKey = config.getEngineKey();
final int threadCount = config.getInstanceCount();
@@ -235,6 +235,24 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven
@Override
public void updateModel(final AxArtifactKey incomingEngineServiceKey, final String apexModelString,
final boolean forceFlag) throws ApexException {
+ AxPolicyModel apexPolicyModel = createModel(incomingEngineServiceKey, apexModelString);
+
+ // Update the model
+ updateModel(incomingEngineServiceKey, apexPolicyModel, forceFlag);
+
+ LOGGER.exit();
+ }
+
+ /**
+ * Method to create model.
+ *
+ * @param incomingEngineServiceKey incoming engine service key
+ * @param apexModelString apex model string
+ * @return apexPolicyModel the policy model
+ * @throws ApexException apex exception
+ */
+ public static AxPolicyModel createModel(final AxArtifactKey incomingEngineServiceKey, final String apexModelString)
+ throws ApexException {
// Check if the engine service key specified is sane
if (incomingEngineServiceKey == null) {
String message = ENGINE_KEY_NOT_SPECIFIED;
@@ -260,11 +278,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven
LOGGER.error(message, e);
throw new ApexException(message, e);
}
-
- // Update the model
- updateModel(incomingEngineServiceKey, apexPolicyModel, forceFlag);
-
- LOGGER.exit();
+ return apexPolicyModel;
}
/**
@@ -314,7 +328,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven
/**
* Execute the model update on the engine instances.
- *
+ *
* @param incomingEngineServiceKey the engine service key to update
* @param apexModel the model to update the engines with
* @param forceFlag if true, ignore compatibility problems
@@ -322,7 +336,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven
*/
private void executeModelUpdate(final AxArtifactKey incomingEngineServiceKey, final AxPolicyModel apexModel,
final boolean forceFlag) throws ApexException {
-
+
if (!isStopped()) {
stopEngines(incomingEngineServiceKey);
}
@@ -458,7 +472,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven
// Start the engine
engineWorkerMap.get(engineKey).start(engineKey);
-
+
// Check if periodic events should be turned on
if (periodicEventPeriod > 0) {
startPeriodicEvents(periodicEventPeriod);
@@ -478,7 +492,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven
periodicEventGenerator.cancel();
periodicEventGenerator = null;
}
-
+
// Stop each engine
for (final EngineService engine : engineWorkerMap.values()) {
if (engine.getState() != AxEngineState.STOPPED) {
diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java
index 4312793e4..c1ef50bd7 100644
--- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java
+++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java
@@ -1,6 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +23,8 @@ package org.onap.policy.apex.service.parameters;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
-
import java.io.FileReader;
-
+import lombok.Setter;
import org.onap.policy.apex.core.engine.EngineParameters;
import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments;
import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters;
@@ -46,6 +46,9 @@ import org.slf4j.ext.XLoggerFactory;
public class ApexParameterHandler {
private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexParameterHandler.class);
+ @Setter
+ private boolean keepParameterServiceFlag;
+
/**
* Read the parameters from the parameter file.
*
@@ -54,8 +57,11 @@ public class ApexParameterHandler {
* @throws ParameterException on parameter exceptions
*/
public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ParameterException {
- // Clear all existing parameters
- ParameterService.clear();
+ // when populating parameters for multiple policies, do not clear the ParameterService already registered
+ // otherwise clear all existing parameters
+ if (!keepParameterServiceFlag) {
+ ParameterService.clear();
+ }
ApexParameters parameters = null;
@@ -112,8 +118,12 @@ public class ApexParameterHandler {
LOGGER.info(returnMessage);
}
- // Register the parameters with the parameter service
- registerParameters(parameters);
+ // engine parameters in multiple policies are expected to be same.
+ // no need to do registration if already registered
+ if (!keepParameterServiceFlag) {
+ // Register the parameters with the parameter service
+ registerParameters(parameters);
+ }
return parameters;
}
diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java
index 6ed3c755d..86ae99ec7 100644
--- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java
+++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java
@@ -5,15 +5,15 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
@@ -26,10 +26,14 @@ import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
-
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.After;
import org.junit.Test;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
+import org.onap.policy.apex.service.parameters.ApexParameters;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
/**
* Test the ApexMain class.
@@ -37,6 +41,16 @@ import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
public class ApexMainTest {
private PrintStream stdout = System.out;
+ /**
+ * Method for cleanup after each test.
+ *
+ * @throws Exception if an error occurs
+ */
+ @After
+ public void teardown() throws Exception {
+ System.setOut(stdout);
+ }
+
@Test
public void testNullParameters() throws ApexException {
OutputStream outContent = new ByteArrayOutputStream();
@@ -47,8 +61,6 @@ public class ApexMainTest {
final String outString = outContent.toString();
- System.setOut(stdout);
-
assertTrue(outString.contains("Apex configuration file was not specified as an argument"));
}
@@ -65,8 +77,6 @@ public class ApexMainTest {
final String outString = outContent.toString();
- System.setOut(stdout);
-
assertTrue(outString.contains("invalid command line arguments specified : Unrecognized option: -whee"));
}
@@ -83,8 +93,6 @@ public class ApexMainTest {
final String outString = outContent.toString();
- System.setOut(stdout);
-
assertTrue(outString.contains("usage: org.onap.policy.apex.service.engine.main.ApexMain [options...]"));
}
@@ -101,8 +109,6 @@ public class ApexMainTest {
final String outString = outContent.toString();
- System.setOut(stdout);
-
assertTrue(outString.contains("parameter group has status INVALID"));
}
@@ -114,14 +120,13 @@ public class ApexMainTest {
String[] args = { "-c", "src/test/resources/parameters/correctParams.json" };
final ApexMain apexMain = new ApexMain(args);
- assertEquals("MyApexEngine", apexMain.getParameters().getEngineServiceParameters().getName());
+ assertEquals("MyApexEngine",
+ apexMain.getApexParametersMap().values().iterator().next().getEngineServiceParameters().getName());
ThreadUtilities.sleep(200);
apexMain.shutdown();
final String outString = outContent.toString();
- System.setOut(stdout);
-
assertTrue(outString.contains("Added the action listener to the engine"));
}
@@ -133,7 +138,8 @@ public class ApexMainTest {
String[] args = { "-c", "src/test/resources/parameters/correctParamsJavaProperties.json" };
final ApexMain apexMain = new ApexMain(args);
- assertEquals("MyApexEngine", apexMain.getParameters().getEngineServiceParameters().getName());
+ assertEquals("MyApexEngine",
+ apexMain.getApexParametersMap().values().iterator().next().getEngineServiceParameters().getName());
assertEquals("trust-store-file", System.getProperty("javax.net.ssl.trustStore"));
assertEquals("Pol1cy_0nap", System.getProperty("javax.net.ssl.trustStorePassword"));
@@ -143,8 +149,55 @@ public class ApexMainTest {
ThreadUtilities.sleep(10000);
final String outString = outContent.toString();
- System.setOut(stdout);
+ assertTrue(outString.contains("Added the action listener to the engine"));
+ }
+ @Test
+ public void testCorrectParametersWithMultiplePolicies() throws ApexException {
+ OutputStream outContent = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outContent));
+ Map<ToscaPolicyIdentifier, String[]> argsMap = new HashMap<ToscaPolicyIdentifier, String[]>();
+ String[] args = {"-c", "src/test/resources/parameters/correctParams.json", "-m",
+ "src/test/resources/policymodels/SmallModel.json"};
+ argsMap.put(new ToscaPolicyIdentifier("id1", "v1"), args);
+ final ApexMain apexMain = new ApexMain(argsMap);
+ ApexParameters apexParam = (ApexParameters) apexMain.getApexParametersMap().values().toArray()[0];
+ assertEquals("MyApexEngine", apexParam.getEngineServiceParameters().getName());
+ apexMain.shutdown();
+ final String outString = outContent.toString();
assertTrue(outString.contains("Added the action listener to the engine"));
}
+
+ @Test
+ public void testInCorrectParametersWithMultiplePolicies() throws ApexException {
+ OutputStream outContent = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outContent));
+ Map<ToscaPolicyIdentifier, String[]> argsMap = new HashMap<ToscaPolicyIdentifier, String[]>();
+ String[] args = {"-c", "src/test/resources/parameters/correctParams.json", "-m",
+ "src/test/resources/policymodels/SmallModel.json"};
+ argsMap.put(new ToscaPolicyIdentifier("id1", "v1"), args);
+ argsMap.put(new ToscaPolicyIdentifier("id2", "v2"), args);
+ final ApexMain apexMain = new ApexMain(argsMap);
+ ApexParameters apexParam = (ApexParameters) apexMain.getApexParametersMap().values().toArray()[0];
+ assertEquals("MyApexEngine", apexParam.getEngineServiceParameters().getName());
+ apexMain.shutdown();
+ final String outString = outContent.toString();
+ assertTrue(outString.contains("I/O Parameters for id2:v2 has duplicates. So this policy is not executed"));
+ assertTrue(apexMain.getApexParametersMap().size() == 1); // only id1:v1 is kept in the map, id2:v2 failed
+ }
+
+ @Test
+ public void testInvalidArgsWithMultiplePolicies() throws ApexException {
+ OutputStream outContent = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outContent));
+ Map<ToscaPolicyIdentifier, String[]> argsMap = new HashMap<ToscaPolicyIdentifier, String[]>();
+ String[] args = {"-c", "file1", "-m", "file2"};
+ argsMap.put(new ToscaPolicyIdentifier("id1", "v1"), args);
+ final ApexMain apexMain = new ApexMain(argsMap);
+ final String outString = outContent.toString();
+ apexMain.shutdown();
+ assertTrue(
+ outString.contains("Arguments validation failed") && outString.contains("start of Apex service failed"));
+ assertTrue(apexMain.getApexParametersMap().isEmpty()); // No policy is running in the engine
+ }
}