diff options
author | FrancescoFioraEst <francesco.fiora@est.tech> | 2022-08-19 12:09:51 +0100 |
---|---|---|
committer | FrancescoFioraEst <francesco.fiora@est.tech> | 2022-08-30 09:25:21 +0100 |
commit | 35e46060a44f17c68cff654c5f65e3831af03847 (patch) | |
tree | 273af6038f340070a4e253d3ba340a4d8e826cc8 /examples/examples-acm/src | |
parent | fddb2c8664d73ea6041c3111f4a5e894c7c5103c (diff) |
Add example policy for AC element microservice test
Issue-ID: POLICY-4307
Change-Id: I0275bbacb3d2689f50f93eef541cd43601aab8ef
Signed-off-by: FrancescoFioraEst <francesco.fiora@est.tech>
Diffstat (limited to 'examples/examples-acm/src')
9 files changed, 514 insertions, 0 deletions
diff --git a/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestRestDmaapEndpoint.java b/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestRestDmaapEndpoint.java new file mode 100644 index 000000000..a3af9406c --- /dev/null +++ b/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestRestDmaapEndpoint.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.apex.examples.acm; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class AcmTestRestDmaapEndpoint creates rest server endpoints for simulating sending/receiving events on DMaaP. + */ +@Path("/") +@Produces("application/json") +public class AcmTestRestDmaapEndpoint { + + private static final XLogger LOGGER = XLoggerFactory.getXLogger(AcmTestRestDmaapEndpoint.class); + private final Object lock = new Object(); + private static String loggedOutputEvent = ""; + private static final AtomicInteger counter = new AtomicInteger(1); + + /** + * DMaaP input of events. This input event triggers the policy + * + * @param timeout the timeout to wait for + * @return the response + */ + @Path("events/AC_ELEMENT_MSG/APEX/1") + @GET + public Response getMessages(@QueryParam("timeout") final int timeout) { + String createRequest = "{\"messageType\":\"STATUS\"," + + "\"elementId\":{\"name\":\"onap.policy.clamp.ac.startertobridge\",\"version\":\"1.0.0\"}," + + "\"message\":\"starter: onap.policy.clamp.ac.starter 1.0.0\",\"messageId\":\"" + + counter.incrementAndGet() + "\",\"timestamp\":\"2022-08-19T07:37:01.198592Z\"}"; + LOGGER.info("Create request received: \n {}", createRequest); + + return Response.status(200).entity(List.of(createRequest)).build(); + } + + /** + * Post new message. + * + * @param jsonString the message + * @return the response + */ + @Path("events/POLICY_UPDATE_MSG") + @POST + public Response policyMessage(final String jsonString) { + LOGGER.info("\n*** POLICY LOG ENTRY START ***\n {} \n *** POLICY LOG ENTRY END ***", jsonString); + synchronized (lock) { + loggedOutputEvent += jsonString + "\n"; + } + return Response.status(200).build(); + } + + /** + * Get the logged event for test verification. + * + * @return the response + */ + @Path("events/getLoggedEvent") + @GET + public Response getDetails() { + String loggedEvent; + synchronized (lock) { + loggedEvent = loggedOutputEvent; + } + if (null == loggedEvent) { + return Response.status(500).entity("Error: Log event not yet generated.").build(); + } + return Response.status(200).entity(loggedEvent).build(); + } +} diff --git a/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestServerDmaap.java b/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestServerDmaap.java new file mode 100644 index 000000000..1d9d56a4a --- /dev/null +++ b/examples/examples-acm/src/main/java/org/onap/policy/apex/examples/acm/AcmTestServerDmaap.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.apex.examples.acm; + +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; +import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.onap.policy.common.utils.network.NetworkUtil; + +/** + * The Class AcmTestServerDmaap that manages test servers for REST requests for the test. + */ +public class AcmTestServerDmaap implements AutoCloseable { + private static final String HOST = "localhost"; + private HttpServletServer restServer; + private int restServerPort = 3904; + + /** + * Instantiates a new REST simulator for DMaaP requests. + */ + public AcmTestServerDmaap() { + restServer = HttpServletServerFactoryInstance.getServerFactory().build("AcmTestRestDmaapEndpoint", false, HOST, + restServerPort, "/", false, false); + restServer.addServletClass(null, AcmTestRestDmaapEndpoint.class.getName()); + restServer.setSerializationProvider(GsonMessageBodyHandler.class.getName()); + restServer.start(); + } + + /** + * Validate the Rest server. + * @throws InterruptedException if is not alive + */ + public void validate() throws InterruptedException { + if (!NetworkUtil.isTcpPortOpen(HOST, restServerPort, 50, 200L)) { + throw new IllegalStateException("port " + restServerPort + " is still not in use"); + } + } + + @Override + public void close() throws Exception { + if (restServer != null) { + restServer.stop(); + restServer = null; + } + } +} diff --git a/examples/examples-acm/src/main/resources/examples/config/apexACM/ApexConfig.json b/examples/examples-acm/src/main/resources/examples/config/apexACM/ApexConfig.json new file mode 100644 index 000000000..6a2feaaa0 --- /dev/null +++ b/examples/examples-acm/src/main/resources/examples/config/apexACM/ApexConfig.json @@ -0,0 +1,72 @@ +{ + "engineServiceParameters": { + "name": "MyApexEngine", + "version": "0.0.1", + "id": 45, + "instanceCount": 2, + "deploymentPort": 12561, + "engineParameters": { + "executorParameters": { + "JAVASCRIPT": { + "parameterClassName": "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters" + } + }, + "contextParameters": { + "parameterClassName": "org.onap.policy.apex.context.parameters.ContextParameters", + "schemaParameters": { + "Json": { + "parameterClassName": "org.onap.policy.apex.plugins.context.schema.json.JsonSchemaHelperParameters" + } + } + } + } + }, + "eventInputParameters": { + "DmaapConsumer": { + "carrierTechnologyParameters": { + "carrierTechnology": "RESTCLIENT", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", + "parameters": { + "url": "http://localhost:3904/events/AC_ELEMENT_MSG/APEX/1?timeout=30000" + } + }, + "eventProtocolParameters": { + "eventProtocol": "JSON", + "parameters": { + "pojoField": "DmaapResponseEvent" + } + }, + "eventName": "AcElementEvent", + "eventNameFilter": "AcElementEvent" + } + }, + "eventOutputParameters": { + "logOutputter": { + "carrierTechnologyParameters": { + "carrierTechnology": "FILE", + "parameters": { + "fileName": "outputevents.log" + } + }, + "eventProtocolParameters": { + "eventProtocol": "JSON" + } + }, + "DmaapReplyProducer": { + "carrierTechnologyParameters": { + "carrierTechnology": "RESTCLIENT", + "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restclient.RestClientCarrierTechnologyParameters", + "parameters": { + "url": "http://localhost:3904/events/POLICY_UPDATE_MSG" + } + }, + "eventProtocolParameters": { + "eventProtocol": "JSON", + "parameters": { + "pojoField": "DmaapResponseStatusEvent" + } + }, + "eventNameFilter": "(LogEvent|DmaapResponseStatusEvent)" + } + } +} diff --git a/examples/examples-acm/src/main/resources/examples/events/apexACM/LogEvent.json b/examples/examples-acm/src/main/resources/examples/events/apexACM/LogEvent.json new file mode 100644 index 000000000..c7c16f094 --- /dev/null +++ b/examples/examples-acm/src/main/resources/examples/events/apexACM/LogEvent.json @@ -0,0 +1,10 @@ +{ + "name": "LogEvent", + "version": "0.0.1", + "nameSpace": "org.onap.policy.apex.ac.element", + "source": "APEX", + "target": "Dmaap", + "toscaPolicyState": "", + "final_status": "FINAL_SUCCESS", + "message": "Operation successfully completed." +}
\ No newline at end of file diff --git a/examples/examples-acm/src/main/resources/logic/ForwardPayloadTask.js b/examples/examples-acm/src/main/resources/logic/ForwardPayloadTask.js new file mode 100644 index 000000000..d48b0dcb7 --- /dev/null +++ b/examples/examples-acm/src/main/resources/logic/ForwardPayloadTask.js @@ -0,0 +1,58 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Nordix. All rights reserved. + * ================================================================================ + * 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========================================================= + */ + +executor.logger.info(executor.subject.id); +executor.logger.info(executor.inFields); + +var msgResponse = executor.inFields.get('DmaapResponseEvent'); +executor.logger.info('Task in progress with mesages: ' + msgResponse); + +var elementId = msgResponse.get('elementId').get('name'); + +if (msgResponse.get('messageType') == 'STATUS' && + (elementId == 'onap.policy.clamp.ac.startertobridge' + || elementId == 'onap.policy.clamp.ac.bridgetosink')) { + + var receiverId = ''; + if (elementId == 'onap.policy.clamp.ac.startertobridge') { + receiverId = 'onap.policy.clamp.ac.bridge'; + } else { + receiverId = 'onap.policy.clamp.ac.sink'; + } + + var elementIdResponse = new java.util.HashMap(); + elementIdResponse.put('name', receiverId); + elementIdResponse.put('version', msgResponse.get('elementId').get('version')); + + var dmaapResponse = new java.util.HashMap(); + dmaapResponse.put('elementId', elementIdResponse); + + var message = msgResponse.get('message') + ' trace added from policy'; + dmaapResponse.put('message', message); + dmaapResponse.put('messageType', 'STATUS'); + dmaapResponse.put('messageId', msgResponse.get('messageId')); + dmaapResponse.put('timestamp', msgResponse.get('timestamp')); + + executor.logger.info('Sending forwarding Event to Ac element: ' + dmaapResponse); + + executor.outFields.put('DmaapResponseStatusEvent', dmaapResponse); +} + +true; diff --git a/examples/examples-acm/src/main/resources/policy/APEXacElementPolicy.apex b/examples/examples-acm/src/main/resources/policy/APEXacElementPolicy.apex new file mode 100644 index 000000000..54a89459d --- /dev/null +++ b/examples/examples-acm/src/main/resources/policy/APEXacElementPolicy.apex @@ -0,0 +1,80 @@ +#------------------------------------------------------------------------------- +# ============LICENSE_START======================================================= +# Copyright (C) 2022 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========================================================= +#------------------------------------------------------------------------------- + +model create name=APEXacElementPolicy + +## +## SCHEMAS +## + +schema create name=SimpleStringType flavour=Java schema=java.lang.String +schema create name=UUIDType flavour=Java schema=java.util.UUID +schema create name=SimpleIntType flavour=Java schema=java.lang.Integer + +schema create name=ACEventType flavour=Json schema=LS +#MACROFILE:"src/main/resources/schemas/ACEventType.json" +LE + +## +## EVENTS +## + +album create name=ACElementAlbum scope=policy writable=true schemaName=ACEventType + +# Incoming event +event create name=AcElementEvent version=0.0.1 nameSpace=org.onap.policy.apex.ac.element source=Dmaap target=APEX toscaPolicyState=ENTRY +event parameter create name=AcElementEvent parName=DmaapResponseEvent schemaName=ACEventType + +# Forwarding event +event create name=DmaapResponseStatusEvent nameSpace=org.onap.policy.apex.ac.element source=APEX target=Dmaap +event parameter create name=DmaapResponseStatusEvent parName=DmaapResponseStatusEvent schemaName=ACEventType + +# Log event +event create name=LogEvent nameSpace=org.onap.policy.apex.ac.element source=APEX target=file +event parameter create name=LogEvent parName=final_status schemaName=SimpleStringType +event parameter create name=LogEvent parName=message schemaName=SimpleStringType + +## +## TASKS +## + +task create name=ForwardPayloadTask +task contextref create name=ForwardPayloadTask albumName=ACElementAlbum +task inputfield create name=ForwardPayloadTask fieldName=DmaapResponseEvent schemaName=ACEventType +task logic create name=ForwardPayloadTask logicFlavour=JAVASCRIPT logic=LS +#MACROFILE:"src/main/resources/logic/ForwardPayloadTask.js" +LE + + +## +## POLICIES +## + +# Policy ReceiveEventPolicy +policy create name=ReceiveEventPolicy template=Freestyle firstState=DecideForwardingState + + +# State DecideForwardingState +policy state create name=ReceiveEventPolicy stateName=DecideForwardingState triggerName=AcElementEvent defaultTaskName=ForwardPayloadTask +policy state output create name=ReceiveEventPolicy stateName=DecideForwardingState outputName=CreateForwardPayload eventName=DmaapResponseStatusEvent nextState=NULL +policy state taskref create name=ReceiveEventPolicy stateName=DecideForwardingState taskName=ForwardPayloadTask outputType=DIRECT outputName=CreateForwardPayload + + +validate diff --git a/examples/examples-acm/src/main/resources/schemas/ACEventType.json b/examples/examples-acm/src/main/resources/schemas/ACEventType.json new file mode 100644 index 000000000..1e10c33fe --- /dev/null +++ b/examples/examples-acm/src/main/resources/schemas/ACEventType.json @@ -0,0 +1,32 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "elementId": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "version": { + "type": "string" + } + }, + "required": [ + "name", + "version" + ] + }, + "message": { + "type": "string" + }, + "messageType": { + "type": "string" + } + }, + "required": [ + "elementId", + "message", + "messageType" + ] +} diff --git a/examples/examples-acm/src/main/resources/tosca/ToscaTemplate.json b/examples/examples-acm/src/main/resources/tosca/ToscaTemplate.json new file mode 100644 index 000000000..1ca4098ec --- /dev/null +++ b/examples/examples-acm/src/main/resources/tosca/ToscaTemplate.json @@ -0,0 +1,17 @@ +{ + "tosca_definitions_version": "tosca_simple_yaml_1_1_0", + "topology_template": { + "policies": [ + { + "onap.policies.native.apex.ac.element": { + "type": "onap.policies.native.Apex", + "type_version": "1.0.0", + "name": "onap.policies.native.apex.ac.element", + "version": "1.0.0", + "properties": { + } + } + } + ] + } +} diff --git a/examples/examples-acm/src/test/java/org/onap/policy/apex/examples/acm/TestApexAcmExample.java b/examples/examples-acm/src/test/java/org/onap/policy/apex/examples/acm/TestApexAcmExample.java new file mode 100644 index 000000000..5b8cbdfe7 --- /dev/null +++ b/examples/examples-acm/src/test/java/org/onap/policy/apex/examples/acm/TestApexAcmExample.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 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.apex.examples.acm; + +import static org.awaitility.Awaitility.await; + +import java.util.concurrent.TimeUnit; +import javax.ws.rs.client.ClientBuilder; +import org.junit.Test; +import org.onap.policy.apex.auth.clieditor.tosca.ApexCliToscaEditorMain; +import org.onap.policy.apex.service.engine.main.ApexMain; + +/** + * Test class to run an example policy for ACM interaction. Event received on + * message topic (dummy REST Endpoint here) and triggers a new message. + */ +public class TestApexAcmExample { + + @Test + public void testExample() { + try (var dmmap = new AcmTestServerDmaap()) { + dmmap.validate(); + + // @formatter:off + final String[] cliArgs = new String[] { + "-c", + "src/main/resources/policy/APEXacElementPolicy.apex", + "-l", + "target/APEXacElementPolicyModel.log", + "-ac", + "src/main/resources/examples/config/apexACM/ApexConfig.json", + "-t", + "src/main/resources/tosca/ToscaTemplate.json", + "-ot", + "target/classes/APEXacElementPolicy.json" + }; + // @formatter:on + + new ApexCliToscaEditorMain(cliArgs); + + // @formatter:off + final String[] apexArgs = { + "-rfr", + "target/classes", + "-p", + "target/classes/APEXacElementPolicy.json" + }; + // @formatter:on + + final var client = ClientBuilder.newClient(); + final var apexMain = new ApexMain(apexArgs); + + await().atMost(5000, TimeUnit.MILLISECONDS).until(() -> apexMain.isAlive()); + + String getLoggedEventUrl = "http://localhost:3904/events/getLoggedEvent"; + await().atMost(20000, TimeUnit.MILLISECONDS).until(() -> { + var response = client.target(getLoggedEventUrl).request("application/json").get(); + var responseEntity = response.readEntity(String.class); + return responseEntity != null && !responseEntity.isEmpty(); + }); + apexMain.shutdown(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} |