diff options
Diffstat (limited to 'models-sim/policy-models-sim-pdp/src/main/java/org')
16 files changed, 1661 insertions, 0 deletions
diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorActivator.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorActivator.java new file mode 100644 index 000000000..be396de05 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorActivator.java @@ -0,0 +1,212 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp; + +import java.util.List; +import java.util.Properties; + +import lombok.Getter; +import lombok.Setter; + + +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.common.utils.services.ServiceManager; +import org.onap.policy.common.utils.services.ServiceManagerException; +import org.onap.policy.models.pdp.enums.PdpMessageType; +import org.onap.policy.models.sim.pdp.comm.PdpStateChangeListener; +import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher; +import org.onap.policy.models.sim.pdp.comm.PdpUpdateListener; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException; +import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class activates the PdpSimulator as a complete service together with all its handlers. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorActivator { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorActivator.class); + private final PdpSimulatorParameterGroup pdpSimulatorParameterGroup; + private List<TopicSink> topicSinks;// topics to which pdp sends pdp status + private List<TopicSource> topicSources; // topics to which pdp listens to for messages from pap. + private static final String[] MSG_TYPE_NAMES = { "messageName" }; + + /** + * Listens for messages on the topic, decodes them into a message, and then dispatches them. + */ + private final MessageTypeDispatcher msgDispatcher; + + /** + * Used to manage the services. + */ + private ServiceManager manager; + + + @Getter + @Setter(lombok.AccessLevel.PRIVATE) + private volatile boolean alive = false; + + /** + * Instantiate the activator for onappf PDP-A. + * + * @param pdpSimulatorParameterGroup the parameters for the onappf PDP-A service + * @param topicProperties properties used to configure the topics + */ + public PdpSimulatorActivator(final PdpSimulatorParameterGroup pdpSimulatorParameterGroup, + final Properties topicProperties) { + + topicSinks = TopicEndpoint.manager.addTopicSinks(topicProperties); + topicSources = TopicEndpoint.manager.addTopicSources(topicProperties); + + final int random = (int) (Math.random() * 1000); + final String instanceId = "pdp_" + random; + LOGGER.debug("PdpSimulatorActivator initializing with instance id:" + instanceId); + try { + this.pdpSimulatorParameterGroup = pdpSimulatorParameterGroup; + this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES); + } catch (final RuntimeException e) { + throw new PdpSimulatorRunTimeException(e); + } + + final PdpUpdateListener pdpUpdateListener = new PdpUpdateListener(); + final PdpStateChangeListener pdpStateChangeListener = new PdpStateChangeListener(); + // @formatter:off + this.manager = new ServiceManager() + .addAction("topics", + () -> TopicEndpoint.manager.start(), + () -> TopicEndpoint.manager.shutdown()) + .addAction("set alive", + () -> setAlive(true), + () -> setAlive(false)) + .addAction("register pdp status context object", + () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, + new PdpMessageHandler().createPdpStatusFromParameters(instanceId, + pdpSimulatorParameterGroup.getPdpStatusParameters())), + () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT)) + .addAction("topic sinks", + () -> Registry.register(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS, topicSinks), + () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS)) + .addAction("Pdp Status publisher", + () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, + new PdpStatusPublisher(topicSinks, + pdpSimulatorParameterGroup.getPdpStatusParameters().getTimeIntervalMs())), + () -> stopAndRemovePdpStatusPublisher()) + .addAction("Register pdp update listener", + () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener), + () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name())) + .addAction("Register pdp state change request dispatcher", + () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener), + () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name())) + .addAction("Message Dispatcher", + () -> registerMsgDispatcher(), + () -> unregisterMsgDispatcher()); + + // @formatter:on + } + + /** + * Method to stop and unregister the pdp status publisher. + */ + private void stopAndRemovePdpStatusPublisher() { + final PdpStatusPublisher pdpStatusPublisher = + Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class); + pdpStatusPublisher.terminate(); + Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + } + + /** + * Initialize PdpSimulator service. + * + * @throws PdpSimulatorException on errors in initializing the service + */ + public void initialize() throws PdpSimulatorException { + if (isAlive()) { + throw new IllegalStateException("activator already initialized"); + } + + try { + LOGGER.debug("PdpSimulator starting as a service . . ."); + manager.start(); + LOGGER.debug("PdpSimulator started as a service"); + } catch (final ServiceManagerException exp) { + LOGGER.error("PdpSimulator service startup failed"); + throw new PdpSimulatorException(exp.getMessage(), exp); + } + } + + /** + * Terminate PdpSimulator. + * + * @throws PdpSimulatorException on errors in terminating the service + */ + public void terminate() throws PdpSimulatorException { + if (!isAlive()) { + throw new IllegalStateException("activator is not running"); + } + try { + final PdpStatusPublisher pdpStatusPublisher = + Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class); + // send a final heartbeat with terminated status + pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus()); + manager.stop(); + Registry.unregister(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR); + } catch (final ServiceManagerException exp) { + LOGGER.error("PdpSimulator termination failed"); + throw new PdpSimulatorException(exp.getMessage(), exp); + } + } + + /** + * Get the parameters used by the activator. + * + * @return pdpSimulatorParameterGroup the parameters of the activator + */ + public PdpSimulatorParameterGroup getParameterGroup() { + return pdpSimulatorParameterGroup; + } + + /** + * Registers the dispatcher with the topic source(s). + */ + private void registerMsgDispatcher() { + for (final TopicSource source : topicSources) { + source.register(msgDispatcher); + } + } + + /** + * Unregisters the dispatcher from the topic source(s). + */ + private void unregisterMsgDispatcher() { + for (final TopicSource source : topicSources) { + source.unregister(msgDispatcher); + } + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorCommandLineArguments.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorCommandLineArguments.java new file mode 100644 index 000000000..fb517e221 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorCommandLineArguments.java @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp; + +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URL; +import java.util.Arrays; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.log4j.chainsaw.Main; + +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException; + +/** + * This class reads and handles command line parameters for the pdp simulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorCommandLineArguments { + + private static final String FILE_MESSAGE_PREAMBLE = " file \""; + private static final int HELP_LINE_LENGTH = 120; + + private final Options options; + private String configurationFilePath = null; + private String propertyFilePath = null; + + /** + * Construct the options for the CLI editor. + */ + public PdpSimulatorCommandLineArguments() { + //@formatter:off + options = new Options(); + options.addOption(Option.builder("h") + .longOpt("help") + .desc("outputs the usage of this command") + .required(false) + .type(Boolean.class) + .build()); + options.addOption(Option.builder("v") + .longOpt("version") + .desc("outputs the version of pdp simulator") + .required(false) + .type(Boolean.class) + .build()); + options.addOption(Option.builder("c") + .longOpt("config-file") + .desc("the full path to the configuration file to use, " + + "the configuration file must be a Json file containing the pdp simulator parameters") + .hasArg() + .argName("CONFIG_FILE") + .required(false) + .type(String.class) + .build()); + options.addOption(Option.builder("p") + .longOpt("property-file") + .desc("the full path to the topic property file to use, " + + "the property file contains the pdp simulator topic properties") + .hasArg() + .argName("PROP_FILE") + .required(false) + .type(String.class) + .build()); + //@formatter:on + } + + /** + * Construct the options for the CLI editor and parse in the given arguments. + * + * @param args The command line arguments + */ + public PdpSimulatorCommandLineArguments(final String[] args) { + // Set up the options with the default constructor + this(); + + // Parse the arguments + try { + parse(args); + } catch (final PdpSimulatorException e) { + throw new PdpSimulatorRunTimeException("parse error on pdp simulator parameters", e); + } + } + + /** + * Parse the command line options. + * + * @param args The command line arguments + * @return a string with a message for help and version, or null if there is no message + * @throws PdpSimulatorException on command argument errors + */ + public String parse(final String[] args) throws PdpSimulatorException { + // Clear all our arguments + setConfigurationFilePath(null); + setPropertyFilePath(null); + + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new PdpSimulatorException("invalid command line arguments specified : " + e.getMessage()); + } + + // Arguments left over after Commons CLI does its stuff + final String[] remainingArgs = commandLine.getArgs(); + + if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 0) { + throw new PdpSimulatorException("too many command line arguments specified : " + Arrays.toString(args)); + } + + if (remainingArgs.length == 1) { + configurationFilePath = remainingArgs[0]; + } + + if (commandLine.hasOption('h')) { + return help(Main.class.getCanonicalName()); + } + + if (commandLine.hasOption('v')) { + return version(); + } + + if (commandLine.hasOption('c')) { + setConfigurationFilePath(commandLine.getOptionValue('c')); + } + + if (commandLine.hasOption('p')) { + setPropertyFilePath(commandLine.getOptionValue('p')); + } + + return null; + } + + /** + * Validate the command line options. + * + * @throws PdpSimulatorException on command argument validation errors + */ + public void validate() throws PdpSimulatorException { + validateReadableFile("pdp simulator configuration", configurationFilePath); + validateReadableFile("pdp simulator properties", propertyFilePath); + } + + /** + * Print version information for pdp simulator. + * + * @return the version string + */ + public String version() { + return ResourceUtils.getResourceAsString("src/main/resources/version.txt"); + } + + /** + * Print help information for pdp simulator. + * + * @param mainClassName the main class name + * @return the help string + */ + public String help(final String mainClassName) { + final HelpFormatter helpFormatter = new HelpFormatter(); + final StringWriter stringWriter = new StringWriter(); + final PrintWriter printWriter = new PrintWriter(stringWriter); + + helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0, + 0, ""); + + return stringWriter.toString(); + } + + /** + * Gets the configuration file path. + * + * @return the configuration file path + */ + public String getConfigurationFilePath() { + return configurationFilePath; + } + + /** + * Gets the full expanded configuration file path. + * + * @return the configuration file path + */ + public String getFullConfigurationFilePath() { + return ResourceUtils.getFilePath4Resource(getConfigurationFilePath()); + } + + /** + * Sets the configuration file path. + * + * @param configurationFilePath the configuration file path + */ + public void setConfigurationFilePath(final String configurationFilePath) { + this.configurationFilePath = configurationFilePath; + + } + + /** + * Check set configuration file path. + * + * @return true, if check set configuration file path + */ + public boolean checkSetConfigurationFilePath() { + return configurationFilePath != null && configurationFilePath.length() > 0; + } + + /** + * Gets the property file path. + * + * @return the property file path + */ + public String getPropertyFilePath() { + return propertyFilePath; + } + + /** + * Gets the full expanded property file path. + * + * @return the property file path + */ + public String getFullPropertyFilePath() { + return ResourceUtils.getFilePath4Resource(getPropertyFilePath()); + } + + /** + * Sets the property file path. + * + * @param propertyFilePath the property file path + */ + public void setPropertyFilePath(final String propertyFilePath) { + this.propertyFilePath = propertyFilePath; + + } + + /** + * Check set property file path. + * + * @return true, if check set property file path + */ + public boolean checkSetPropertyFilePath() { + return propertyFilePath != null && propertyFilePath.length() > 0; + } + + /** + * Validate readable file. + * + * @param fileTag the file tag + * @param fileName the file name + * @throws PdpSimulatorException on the file name passed as a parameter + */ + private void validateReadableFile(final String fileTag, final String fileName) throws PdpSimulatorException { + if (fileName == null || fileName.length() == 0) { + throw new PdpSimulatorException(fileTag + " file was not specified as an argument"); + } + + // The file name refers to a resource on the local file system + final URL fileUrl = ResourceUtils.getUrl4Resource(fileName); + if (fileUrl == null) { + throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + + final File theFile = new File(fileUrl.getPath()); + if (!theFile.exists()) { + throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + if (!theFile.isFile()) { + throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file"); + } + if (!theFile.canRead()) { + throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable"); + } + } + +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorConstants.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorConstants.java new file mode 100644 index 000000000..22dbc4610 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorConstants.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp; + +/** + * Names of various items contained in the Registry. + */ +public class PdpSimulatorConstants { + // Registry keys + public static final String REG_PDP_SIMULATOR_ACTIVATOR = "object:activator/pdp_simulator"; + public static final String REG_PDP_STATUS_OBJECT = "object:pdp/status"; + public static final String REG_PDP_TOSCA_POLICY_LIST = "object:pdp/tosca/policy/list"; + public static final String REG_PDP_STATUS_PUBLISHER = "object:pdp/status/publisher"; + public static final String REG_PDP_TOPIC_SINKS = "object:pdp/topic/sinks"; + + private PdpSimulatorConstants() { + super(); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorMain.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorMain.java new file mode 100644 index 000000000..f5892d5c8 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorMain.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp; + +import java.io.FileInputStream; +import java.util.Arrays; +import java.util.Properties; + + +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class initiates PdpSimulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorMain { + + private static final String PDP_SIMULATOR_FAIL_MSG = "start of pdp simulator failed"; + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorMain.class); + + private PdpSimulatorActivator activator; + private PdpSimulatorParameterGroup parameterGroup; + + /** + * Instantiates the PdpSimulator. + * + * @param args the command line arguments + */ + public PdpSimulatorMain(final String[] args) { + LOGGER.info("In PdpSimulator with parameters ", Arrays.toString(args)); + + // Check the arguments + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + try { + // The arguments return a string if there is a message to print and we should exit + final String argumentMessage = arguments.parse(args); + if (argumentMessage != null) { + LOGGER.debug(argumentMessage); + return; + } + // Validate that the arguments are sane + arguments.validate(); + } catch (final PdpSimulatorException e) { + LOGGER.error(PDP_SIMULATOR_FAIL_MSG, e); + return; + } + + // Read the parameters + try { + parameterGroup = new PdpSimulatorParameterHandler().getParameters(arguments); + } catch (final Exception e) { + LOGGER.error(PDP_SIMULATOR_FAIL_MSG, e); + return; + } + + // Read the properties + final Properties topicProperties = new Properties(); + try { + final String propFile = arguments.getFullPropertyFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + topicProperties.load(stream); + } + } catch (final Exception e) { + LOGGER.error(PDP_SIMULATOR_FAIL_MSG, e); + return; + } + + // create the activator + activator = new PdpSimulatorActivator(parameterGroup, topicProperties); + Registry.register(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR, activator); + // Start the activator + try { + activator.initialize(); + } catch (final PdpSimulatorException e) { + LOGGER.error("start of PdpSimulator failed, used parameters are {}", Arrays.toString(args), e); + Registry.unregister(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR); + return; + } + + // Add a shutdown hook to shut everything down in an orderly manner + Runtime.getRuntime().addShutdownHook(new PdpSimulatorShutdownHookClass()); + + LOGGER.info("Started PdpSimulator service"); + } + + /** + * Get the parameters specified in JSON. + * + * @return parameterGroup the parameters + */ + public PdpSimulatorParameterGroup getParameters() { + return parameterGroup; + } + + + /** + * Shut down Execution. + * + * @throws PdpSimulatorException on shutdown errors + */ + public void shutdown() throws PdpSimulatorException { + // clear the parameterGroup variable + parameterGroup = null; + + // clear the pdp simulator activator + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + /** + * The Class PdpSimulatorShutdownHookClass terminates the pdp simulator when its run method is called. + */ + private class PdpSimulatorShutdownHookClass extends Thread { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + try { + // Shutdown the pdp simulator service and wait for everything to stop + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } catch (final PdpSimulatorException e) { + LOGGER.warn("error occured during shut down of the pdp simulator service", e); + } + } + } + + /** + * The main method. + * + * @param args the arguments + * + */ + public static void main(final String[] args) { + new PdpSimulatorMain(args); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStateChangeListener.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStateChangeListener.java new file mode 100644 index 000000000..ebe493a69 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStateChangeListener.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.comm; + +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.listeners.ScoListener; +import org.onap.policy.common.utils.coder.StandardCoderObject; +import org.onap.policy.models.pdp.concepts.PdpStateChange; +import org.onap.policy.models.sim.pdp.handler.PdpStateChangeMessageHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Listener for Pdp state change messages sent by PAP. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpStateChangeListener extends ScoListener<PdpStateChange> { + private static final Logger LOGGER = LoggerFactory.getLogger(PdpStateChangeListener.class); + + /** + * Constructs the object. + */ + public PdpStateChangeListener() { + super(PdpStateChange.class); + } + + @Override + public void onTopicEvent(final CommInfrastructure infra, final String topic, final StandardCoderObject sco, + final PdpStateChange pdpStateChangeMsg) { + LOGGER.debug("Pdp state change message received from PAP. - {}", pdpStateChangeMsg); + new PdpStateChangeMessageHandler().handlePdpStateChangeEvent(pdpStateChangeMsg); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStatusPublisher.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStatusPublisher.java new file mode 100644 index 000000000..33c9df778 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStatusPublisher.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.comm; + +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is used to send pdp status messages to pap using TopicSinkClient. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpStatusPublisher extends TimerTask { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpStatusPublisher.class); + + private TopicSinkClient topicSinkClient; + private Timer timer; + private long interval; + + /** + * Constructor for instantiating PdpStatusPublisher. + * + * @param topicSinks the topic sinks + * @param interval time interval to send pdp status + */ + public PdpStatusPublisher(final List<TopicSink> topicSinks, final long interval) { + this.topicSinkClient = new TopicSinkClient(topicSinks.get(0)); + this.interval = interval; + timer = new Timer(false); + timer.scheduleAtFixedRate(this, 0, interval); + } + + @Override + public void run() { + final PdpStatus pdpStatus = new PdpMessageHandler().createPdpStatusFromContext(); + topicSinkClient.send(pdpStatus); + LOGGER.debug("Sent heartbeat to PAP - {}", pdpStatus); + } + + /** + * Terminates the current timer. + */ + public void terminate() { + timer.cancel(); + timer.purge(); + } + + /** + * Get the current time interval used by the timer task. + * + * @return interval the current time interval + */ + public long getInterval() { + return interval; + } + + /** + * Method to send pdp status message to pap on demand. + * + * @param pdpStatus the pdp status + */ + public void send(final PdpStatus pdpStatus) { + topicSinkClient.send(pdpStatus); + LOGGER.debug("Sent pdp status message to PAP - {}", pdpStatus); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpUpdateListener.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpUpdateListener.java new file mode 100644 index 000000000..52b1b11f0 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpUpdateListener.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.comm; + +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.listeners.ScoListener; +import org.onap.policy.common.utils.coder.StandardCoderObject; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.sim.pdp.handler.PdpUpdateMessageHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Listener for Pdp update messages sent by PAP. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpUpdateListener extends ScoListener<PdpUpdate> { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpUpdateListener.class); + + /** + * Constructs the object. + */ + public PdpUpdateListener() { + super(PdpUpdate.class); + } + + @Override + public void onTopicEvent(final CommInfrastructure infra, final String topic, final StandardCoderObject sco, + final PdpUpdate pdpUpdateMsg) { + LOGGER.debug("Pdp update message received from PAP - {}", pdpUpdateMsg); + new PdpUpdateMessageHandler().handlePdpUpdateEvent(pdpUpdateMsg); + + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorException.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorException.java new file mode 100644 index 000000000..9d460ad77 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorException.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.exception; + +/** + * This exception will be called if an error occurs in pdp simulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorException extends Exception { + private static final long serialVersionUID = -510646141043975917L; + + /** + * Instantiates a new pdp simulator exception with a message. + * + * @param message the message + */ + public PdpSimulatorException(final String message) { + super(message); + } + + /** + * Instantiates a new pdp simulator exception caused by an exception. + * + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorException(final Exception exception) { + super(exception); + } + + /** + * Instantiates a new pdp simulator exception with a message and a caused by an exception. + * + * @param message the message + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorException(final String message, final Exception exception) { + super(message, exception); + } + +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorRunTimeException.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorRunTimeException.java new file mode 100644 index 000000000..4b6839f56 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorRunTimeException.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.exception; + +/** + * This runtime exception will be called if a runtime error occurs when using pdp simulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorRunTimeException extends RuntimeException { + private static final long serialVersionUID = -6024353312002272098L; + + /** + * Instantiates a new pdp simulator runtime exception with a message. + * + * @param message the message + */ + public PdpSimulatorRunTimeException(final String message) { + super(message); + } + + /** + * Instantiates a new pdp simulator runtime exception caused by an exception. + * + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorRunTimeException(final Exception exception) { + super(exception); + } + + /** + * Instantiates a new pdp simulator runtime exception with a message and caused by an exception. + * + * @param message the message + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorRunTimeException(final String message, final Exception exception) { + super(message, exception); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java new file mode 100644 index 000000000..d4296c6df --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.handler; + +import java.util.ArrayList; +import java.util.List; + + +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpResponseDetails; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.enums.PdpHealthStatus; +import org.onap.policy.models.pdp.enums.PdpResponseStatus; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.parameters.PdpStatusParameters; +import org.onap.policy.models.sim.pdp.parameters.ToscaPolicyTypeIdentifierParameters; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; + +/** + * This class supports the handling of pdp messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpMessageHandler { + + /** + * Method to create PdpStatus message from the parameters which will be saved to the context. + * + * @param instanceId instance id of the pdp + * @param pdpStatusParameters pdp status parameters read from the configuration file + * + * @return pdpStatus the pdp status message + */ + public PdpStatus createPdpStatusFromParameters(final String instanceId, + final PdpStatusParameters pdpStatusParameters) { + final PdpStatus pdpStatus = new PdpStatus(); + pdpStatus.setPdpType(pdpStatusParameters.getPdpType()); + pdpStatus.setState(PdpState.PASSIVE); + pdpStatus.setHealthy(PdpHealthStatus.HEALTHY); + pdpStatus.setDescription(pdpStatusParameters.getDescription()); + pdpStatus.setName(instanceId); + pdpStatus.setSupportedPolicyTypes(getSupportedPolicyTypesFromParameters(pdpStatusParameters)); + return pdpStatus; + } + + /** + * Method to get supported policy types from the parameters. + * + * @param pdpStatusParameters pdp status parameters + * @return supportedPolicyTypes list of PolicyTypeIdent + */ + private List<ToscaPolicyTypeIdentifier> getSupportedPolicyTypesFromParameters( + final PdpStatusParameters pdpStatusParameters) { + final List<ToscaPolicyTypeIdentifier> supportedPolicyTypes = + new ArrayList<>(pdpStatusParameters.getSupportedPolicyTypes().size()); + for (final ToscaPolicyTypeIdentifierParameters policyTypeIdentParameters : pdpStatusParameters + .getSupportedPolicyTypes()) { + supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(policyTypeIdentParameters.getName(), + policyTypeIdentParameters.getVersion())); + } + return supportedPolicyTypes; + } + + /** + * Method to create PdpStatus message from the context, which is to be sent by pdp simulator to pap. + * + * @return PdpStatus the pdp status message + */ + public PdpStatus createPdpStatusFromContext() { + final PdpStatus pdpStatusContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + final PdpStatus pdpStatus = new PdpStatus(); + pdpStatus.setName(pdpStatusContext.getName()); + pdpStatus.setPdpType(pdpStatusContext.getPdpType()); + pdpStatus.setState(pdpStatusContext.getState()); + pdpStatus.setHealthy(pdpStatusContext.getHealthy()); + pdpStatus.setDescription(pdpStatusContext.getDescription()); + pdpStatus.setSupportedPolicyTypes(pdpStatusContext.getSupportedPolicyTypes()); + pdpStatus.setPolicies(pdpStatusContext.getPolicies()); + pdpStatus.setPdpGroup(pdpStatusContext.getPdpGroup()); + pdpStatus.setPdpSubgroup(pdpStatusContext.getPdpSubgroup()); + return pdpStatus; + } + + /** + * Method to get a final pdp status when the simulator is shut down. + * + * @return PdpStatus the pdp status message + */ + public PdpStatus getTerminatedPdpStatus() { + final PdpStatus pdpStatusInContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + pdpStatusInContext.setState(PdpState.TERMINATED); + pdpStatusInContext.setDescription("Pdp Simulator shutting down."); + return createPdpStatusFromContext(); + } + + /** + * Method create PdpResponseDetails which will be sent as part of pdp status to PAP. + * + * @param requestId request id of the PdpUpdate message from pap + * @param status response status to be sent back + * @param responseMessage response message to be sent back + * + * @return PdpResponseDetails + */ + public PdpResponseDetails createPdpResonseDetails(final String requestId, final PdpResponseStatus status, + final String responseMessage) { + final PdpResponseDetails pdpResponseDetails = new PdpResponseDetails(); + pdpResponseDetails.setResponseTo(requestId); + pdpResponseDetails.setResponseStatus(status); + pdpResponseDetails.setResponseMessage(responseMessage); + return pdpResponseDetails; + } + + /** + * Method to retrieve list of ToscaPolicyIdentifier from the list of ToscaPolicy. + * + * @param policies list of ToscaPolicy + * + * @return policyTypeIdentifiers + */ + public List<ToscaPolicyIdentifier> getToscaPolicyIdentifiers(final List<ToscaPolicy> policies) { + final List<ToscaPolicyIdentifier> policyIdentifiers = new ArrayList<>(policies.size()); + for (final ToscaPolicy policy : policies) { + if (null != policy.getName() && null != policy.getVersion()) { + policyIdentifiers.add(new ToscaPolicyIdentifier(policy.getName(), policy.getVersion())); + } + } + return policyIdentifiers; + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpStateChangeMessageHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpStateChangeMessageHandler.java new file mode 100644 index 000000000..ec1fa25a3 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpStateChangeMessageHandler.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.handler; + +import java.util.List; + +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpResponseDetails; +import org.onap.policy.models.pdp.concepts.PdpStateChange; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.enums.PdpResponseStatus; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class supports the handling of pdp state change messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpStateChangeMessageHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpStateChangeMessageHandler.class); + + /** + * Method which handles a pdp state change event from PAP. + * + * @param pdpStateChangeMsg pdp state change message + */ + public void handlePdpStateChangeEvent(final PdpStateChange pdpStateChangeMsg) { + final PdpStatus pdpStatusContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + final PdpStatusPublisher pdpStatusPublisher = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + final PdpMessageHandler pdpMessageHandler = new PdpMessageHandler(); + PdpResponseDetails pdpResponseDetails = null; + if (pdpStateChangeMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(), + pdpStatusContext.getPdpSubgroup())) { + switch (pdpStateChangeMsg.getState()) { + case PASSIVE: + pdpResponseDetails = handlePassiveState(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler); + break; + case ACTIVE: + pdpResponseDetails = handleActiveState(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler); + break; + default: + break; + } + final PdpStatus pdpStatus = pdpMessageHandler.createPdpStatusFromContext(); + pdpStatus.setResponse(pdpResponseDetails); + pdpStatus.setDescription("Pdp status response message for PdpStateChange"); + pdpStatusPublisher.send(pdpStatus); + } + } + + /** + * Method to handle when the new state from pap is active. + * + * @param pdpStateChangeMsg pdp state change message + * @param pdpStatusContext pdp status object in memory + * @param pdpMessageHandler the pdp message handler + * @return pdpResponseDetails pdp response + */ + private PdpResponseDetails handleActiveState(final PdpStateChange pdpStateChangeMsg, + final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) { + PdpResponseDetails pdpResponseDetails = null; + if (pdpStatusContext.getState().equals(PdpState.ACTIVE)) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp already in active state"); + } else { + final List<ToscaPolicy> policies = Registry.get(PdpSimulatorConstants.REG_PDP_TOSCA_POLICY_LIST); + if (policies.isEmpty()) { + pdpStatusContext.setState(PdpState.ACTIVE); + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "State changed to active. No policies found."); + } else { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp started. State changed to active."); + pdpStatusContext.setState(PdpState.ACTIVE); + } + } + return pdpResponseDetails; + } + + /** + * Method to handle when the new state from pap is passive. + * + * @param pdpStateChangeMsg pdp state change message + * @param pdpStatusContext pdp status object in memory + * @param pdpMessageHandler the pdp message handler + * @return pdpResponseDetails pdp response + */ + private PdpResponseDetails handlePassiveState(final PdpStateChange pdpStateChangeMsg, + final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) { + PdpResponseDetails pdpResponseDetails = null; + if (pdpStatusContext.getState().equals(PdpState.PASSIVE)) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp already in passive state"); + } else { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp state changed from Active to Passive."); + pdpStatusContext.setState(PdpState.PASSIVE); + } + return pdpResponseDetails; + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpUpdateMessageHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpUpdateMessageHandler.java new file mode 100644 index 000000000..94499f43d --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpUpdateMessageHandler.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.handler; + +import java.util.List; + + +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpResponseDetails; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.pdp.enums.PdpResponseStatus; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class supports the handling of pdp update messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpUpdateMessageHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpUpdateMessageHandler.class); + + /** + * Method which handles a pdp update event from PAP. + * + * @param pdpUpdateMsg pdp update message + */ + public void handlePdpUpdateEvent(final PdpUpdate pdpUpdateMsg) { + final PdpMessageHandler pdpMessageHandler = new PdpMessageHandler(); + final PdpStatus pdpStatusContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + PdpResponseDetails pdpResponseDetails = null; + if (pdpUpdateMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(), + pdpStatusContext.getPdpSubgroup())) { + final PdpStatusPublisher pdpStatusPublisher = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + if (checkIfAlreadyHandled(pdpUpdateMsg, pdpStatusContext)) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp already updated"); + } else { + if (null != pdpUpdateMsg.getPdpHeartbeatIntervalMs() && pdpUpdateMsg.getPdpHeartbeatIntervalMs() > 0 + && pdpStatusPublisher.getInterval() != pdpUpdateMsg.getPdpHeartbeatIntervalMs()) { + updateInterval(pdpUpdateMsg.getPdpHeartbeatIntervalMs()); + } + pdpStatusContext.setPdpGroup(pdpUpdateMsg.getPdpGroup()); + pdpStatusContext.setPdpSubgroup(pdpUpdateMsg.getPdpSubgroup()); + pdpStatusContext + .setPolicies(new PdpMessageHandler().getToscaPolicyIdentifiers(pdpUpdateMsg.getPolicies())); + if (pdpStatusContext.getState().equals(PdpState.ACTIVE)) { + if (!pdpUpdateMsg.getPolicies().isEmpty()) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp engine started and policies are running."); + } + } + Registry.registerOrReplace(PdpSimulatorConstants.REG_PDP_TOSCA_POLICY_LIST, pdpUpdateMsg.getPolicies()); + if (null == pdpResponseDetails) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp update successful."); + } + } + final PdpStatusPublisher pdpStatusPublisherTemp = + Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + final PdpStatus pdpStatus = pdpMessageHandler.createPdpStatusFromContext(); + pdpStatus.setResponse(pdpResponseDetails); + pdpStatus.setDescription("Pdp status response message for PdpUpdate"); + pdpStatusPublisherTemp.send(pdpStatus); + } + } + + + /** + * Method checks if the Pdp update message is already handled by checking the values in the context. + * + * @param pdpUpdateMsg pdp update message received from pap + * @param pdpStatusContext values saved in context memory + * @return boolean flag which tells if the information is same or not + */ + private boolean checkIfAlreadyHandled(final PdpUpdate pdpUpdateMsg, final PdpStatus pdpStatusContext) { + return null != pdpStatusContext.getPdpGroup() + && pdpStatusContext.getPdpGroup().equals(pdpUpdateMsg.getPdpGroup()) + && null != pdpStatusContext.getPdpSubgroup() + && pdpStatusContext.getPdpSubgroup().equals(pdpUpdateMsg.getPdpSubgroup()) + && null != pdpStatusContext.getPolicies() && new PdpMessageHandler() + .getToscaPolicyIdentifiers(pdpUpdateMsg.getPolicies()).equals(pdpStatusContext.getPolicies()); + } + + /** + * Method to update the time interval used by the timer task. + * + * @param interval time interval received in the pdp update message from pap + */ + public void updateInterval(final long interval) { + final PdpStatusPublisher pdpStatusPublisher = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + pdpStatusPublisher.terminate(); + final List<TopicSink> topicSinks = Registry.get(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS); + Registry.registerOrReplace(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, + new PdpStatusPublisher(topicSinks, interval)); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterGroup.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterGroup.java new file mode 100644 index 000000000..58c583901 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterGroup.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.parameters; + +import lombok.Getter; + +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for pdp simulator component. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +@NotNull +@NotBlank +@Getter +public class PdpSimulatorParameterGroup extends ParameterGroupImpl { + private PdpStatusParameters pdpStatusParameters; + + /** + * Create the pdp simulator parameter group. + * + * @param name the parameter group name + */ + public PdpSimulatorParameterGroup(final String name) { + super(name); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterHandler.java new file mode 100644 index 000000000..2c5ccebf9 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterHandler.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.parameters; + +import java.io.File; + + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.models.sim.pdp.PdpSimulatorCommandLineArguments; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class handles reading, parsing and validating of pdp simulator parameters from JSON files. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorParameterHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorParameterHandler.class); + private static final Coder CODER = new StandardCoder(); + + /** + * Read the parameters from the parameter file. + * + * @param arguments the arguments passed to pdp simulator + * @return the parameters read from the configuration file + * @throws PdpSimulatorException on parameter exceptions + */ + public PdpSimulatorParameterGroup getParameters(final PdpSimulatorCommandLineArguments arguments) + throws PdpSimulatorException { + PdpSimulatorParameterGroup pdpSimulatorParameterGroup = null; + + // Read the parameters + try { + // Read the parameters from JSON + final File file = new File(arguments.getFullConfigurationFilePath()); + pdpSimulatorParameterGroup = CODER.decode(file, PdpSimulatorParameterGroup.class); + } catch (final CoderException e) { + final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage(); + LOGGER.error(errorMessage, e); + throw new PdpSimulatorException(errorMessage, e); + } + + // The JSON processing returns null if there is an empty file + if (pdpSimulatorParameterGroup == null) { + final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + LOGGER.error(errorMessage); + throw new PdpSimulatorException(errorMessage); + } + + // validate the parameters + final GroupValidationResult validationResult = pdpSimulatorParameterGroup.validate(); + if (!validationResult.isValid()) { + String returnMessage = + "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; + returnMessage += validationResult.getResult(); + + LOGGER.error(returnMessage); + throw new PdpSimulatorException(returnMessage); + } + + return pdpSimulatorParameterGroup; + } + +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpStatusParameters.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpStatusParameters.java new file mode 100644 index 000000000..e59ec52b7 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpStatusParameters.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.parameters; + +import java.util.List; + +import lombok.Getter; + +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for pdpstatus. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +@NotNull +@NotBlank +@Getter +public class PdpStatusParameters extends ParameterGroupImpl { + + @Min(value = 1) + private long timeIntervalMs; + + private String pdpType; + private String description; + private List<ToscaPolicyTypeIdentifierParameters> supportedPolicyTypes; + + public PdpStatusParameters() { + super(PdpStatusParameters.class.getSimpleName()); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/ToscaPolicyTypeIdentifierParameters.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/ToscaPolicyTypeIdentifierParameters.java new file mode 100644 index 000000000..622b41122 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/ToscaPolicyTypeIdentifierParameters.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * 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========================================================= + */ + +package org.onap.policy.models.sim.pdp.parameters; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for PolicyTypeIdent. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +@NotNull +@NotBlank +@Getter +@Setter +@EqualsAndHashCode +public class ToscaPolicyTypeIdentifierParameters { + private String name; + private String version; +} |