2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.template.demo;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
29 import java.io.IOException;
30 import java.net.URLEncoder;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Properties;
35 import java.util.UUID;
37 import org.junit.AfterClass;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.kie.api.runtime.KieSession;
41 import org.kie.api.runtime.rule.FactHandle;
42 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
43 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
44 import org.onap.policy.common.endpoints.event.comm.TopicListener;
45 import org.onap.policy.common.endpoints.event.comm.TopicSink;
46 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
47 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
48 import org.onap.policy.controlloop.ControlLoopEventStatus;
49 import org.onap.policy.controlloop.ControlLoopNotificationType;
50 import org.onap.policy.controlloop.ControlLoopTargetType;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.controlloop.VirtualControlLoopNotification;
53 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
54 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
55 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
56 import org.onap.policy.drools.system.PolicyController;
57 import org.onap.policy.drools.system.PolicyEngine;
58 import org.onap.policy.drools.utils.logging.LoggerUtil;
59 import org.onap.policy.sdnr.PciRequest;
60 import org.onap.policy.sdnr.PciRequestWrapper;
61 import org.onap.policy.sdnr.PciResponse;
62 import org.onap.policy.sdnr.PciResponseWrapper;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 public class VpciControlLoopTest implements TopicListener {
68 private static final Logger logger = LoggerFactory.getLogger(VpciControlLoopTest.class);
70 private static List<? extends TopicSink> noopTopics;
72 private static KieSession kieSession;
73 private static Util.Pair<ControlLoopPolicy, String> pair;
74 private UUID requestId;
77 /* Set environment properties */
81 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "DEBUG");
85 * Setup the simulator.
88 public static void setUpSimulator() {
89 PolicyEngine.manager.configure(new Properties());
90 assertTrue(PolicyEngine.manager.start());
91 Properties noopSinkProperties = new Properties();
92 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "SDNR-CL,POLICY-CL-MGT");
93 noopSinkProperties.put("noop.sink.topics.SDNR-CL.events", "org.onap.policy.sdnr.PciRequestWrapper");
94 noopSinkProperties.put("noop.sink.topics.SDNR-CL.events.custom.gson",
95 "org.onap.policy.sdnr.util.Serialization,gson");
96 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
97 "org.onap.policy.controlloop.VirtualControlLoopNotification");
98 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
99 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
100 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
102 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
103 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
105 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "SDNR-CL",
106 "org.onap.policy.sdnr.PciRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
109 Util.buildGuardSim();
110 } catch (Exception e) {
111 fail(e.getMessage());
114 * Start the kie session
117 kieSession = startSession(
118 "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
119 + "/src/main/resources/__closedLoopControlName__.drl",
120 "src/test/resources/yaml/policy_ControlLoop_vPCI.yaml", "type=operational", "CL_vPCI", "v3.0.0");
121 } catch (IOException e) {
123 logger.debug("Could not create kieSession");
124 fail("Could not create kieSession");
129 * Tear down the simulator.
132 public static void tearDownSimulator() {
134 * Gracefully shut down the kie session
136 kieSession.dispose();
138 PolicyEngine.manager.stop();
139 HttpServletServer.factory.destroy();
140 PolicyController.factory.shutdown();
141 TopicEndpoint.manager.shutdown();
145 public void successTest() {
148 * Allows the PolicyEngine to callback to this object to notify that there is an
149 * event ready to be pulled from the queue
151 for (TopicSink sink : noopTopics) {
152 assertTrue(sink.start());
157 * Create a unique requestId
159 requestId = UUID.randomUUID();
162 * Simulate an onset event the policy engine will receive from DCAE to kick off
163 * processing through the rules
165 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, true);
167 kieSession.fireUntilHalt();
170 * The only fact in memory should be Params
172 assertEquals(1, kieSession.getFactCount());
175 * Print what's left in memory
177 dumpFacts(kieSession);
182 public void aaiGetFailTest() {
185 * Allows the PolicyEngine to callback to this object to notify that there is an
186 * event ready to be pulled from the queue
188 for (TopicSink sink : noopTopics) {
189 assertTrue(sink.start());
194 * Create a unique requestId
196 requestId = UUID.randomUUID();
199 * Simulate an onset event the policy engine will receive from DCAE to kick off
200 * processing through the rules
202 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, false);
204 kieSession.fireUntilHalt();
207 * The only fact in memory should be Params
209 assertEquals(1, kieSession.getFactCount());
212 * Print what's left in memory
214 dumpFacts(kieSession);
219 * This method will start a kie session and instantiate the Policy Engine.
221 * @param droolsTemplate
224 * the yaml file containing the policies
229 * @param policyVersion
230 * version of the policy
231 * @return the kieSession to be used to insert facts
232 * @throws IOException
235 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
236 String policyName, String policyVersion) throws IOException {
239 * Load policies from yaml
241 pair = Util.loadYaml(yamlFile);
243 assertNotNull(pair.first);
244 assertNotNull(pair.first.getControlLoop());
245 assertNotNull(pair.first.getControlLoop().getControlLoopName());
246 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
249 * Construct a kie session
251 final KieSession kieSession = Util.buildContainer(droolsTemplate,
252 pair.first.getControlLoop().getControlLoopName(), policyScope, policyName, policyVersion,
253 URLEncoder.encode(pair.second, "UTF-8"));
256 * Retrieve the Policy Engine
259 logger.debug("======controlloop======");
260 logger.debug(((ControlLoopPolicy) pair.first).toString());
261 logger.debug("======policies======");
262 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
263 logger.debug("============");
272 * org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.
276 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
277 logger.debug("\n============ onTopicEvent!!! ===========\n");
278 logger.debug("topic: {}, event: {}", topic, event);
280 * Pull the object that was sent out to DMAAP and make sure it is a
281 * ControlLoopNoticiation of type active
284 if ("POLICY-CL-MGT".equals(topic)) {
285 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
286 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
287 } else if ("SDNR-CL".equals(topic)) {
288 obj = org.onap.policy.sdnr.util.Serialization.gsonJunit.fromJson(event,
289 org.onap.policy.sdnr.PciRequestWrapper.class);
292 if (obj instanceof VirtualControlLoopNotification) {
293 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
294 String policyName = notification.getPolicyName();
295 logger.debug("Rule Fired: {}", policyName);
296 if (policyName.endsWith("EVENT")) {
297 assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
298 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
299 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
300 assertNotNull(notification.getMessage());
301 assertTrue(notification.getMessage().startsWith("Sending guard query"));
302 } else if (policyName.endsWith("GUARD.RESPONSE")) {
303 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
304 assertNotNull(notification.getMessage());
305 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
306 } else if (policyName.endsWith("GUARD_PERMITTED")) {
307 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
308 assertNotNull(notification.getMessage());
309 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
310 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
312 logger.debug("The operation timed out");
313 fail("Operation Timed Out");
314 } else if (policyName.endsWith("SDNR.RESPONSE")) {
315 assertEquals(ControlLoopNotificationType.OPERATION_SUCCESS, notification.getNotification());
316 assertNotNull(notification.getMessage());
317 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
318 } else if (policyName.endsWith("EVENT.MANAGER")) {
319 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-id"))) {
320 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
323 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
326 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
328 logger.debug("The control loop timed out");
329 fail("Control Loop Timed Out");
331 } else if (obj instanceof PciRequestWrapper) {
333 * The request should be of type PciRequestWrapper and the subrequestid should
336 PciRequestWrapper dmaapRequest = (PciRequestWrapper) obj;
337 PciRequest pciRequest = dmaapRequest.getBody();
338 assertEquals("1", pciRequest.getCommonHeader().getSubRequestId());
340 logger.debug("\n============ SDNR received the request!!! ===========\n");
341 logger.debug("\n============ dmaapRequest ===========\n {} ", dmaapRequest);
342 logger.debug("\n============ pciRequest ===========\n {}", pciRequest);
345 * Simulate a success response from SDNR and insert the response into the
348 PciResponse pciResponse = new PciResponse(pciRequest);
349 pciResponse.getStatus().setCode(200);
350 pciResponse.getStatus().setValue("SUCCESS");
351 StringBuilder sb = new StringBuilder();
352 sb.append("{ \"Configurations\":[ { \"Status\": { \"Code\": 200, \"Value\":"
353 + " \"SUCCESS\" }, \"data\":{ \"FAPService\":{ \"alias\":"
354 + "\"Network1\", \"X0005b9Lte\" : { \"PnfName\" : \"cu1\" }, \"CellConfig\":"
355 + "{ \"LTE\":{ \"RAN\":{ \"Common\":{ \"CellIdentity\":" + "\"1\" } } } } } } } ] }");
357 pciResponse.setPayload(sb.toString());
358 PciResponseWrapper dmaapResponse = new PciResponseWrapper();
359 dmaapResponse.setBody(pciResponse);
360 dmaapResponse.setType("response");
361 logger.debug("\n============ SDNR sending response!!! ===========\n");
362 logger.debug("\n============ dmaapResponse ===========\n {}", dmaapResponse);
363 logger.debug("\n============ pciResponse ===========\n {}", pciResponse);
364 kieSession.insert(dmaapResponse);
369 * This method is used to simulate event messages from DCAE that start the
370 * control loop (onset message).
373 * the controlLoopName comes from the policy
375 * the requestId for this event
379 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
380 boolean isEnriched) {
381 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
382 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
383 event.setRequestId(requestId);
384 event.setTarget("generic-vnf.vnf-id");
385 event.setTargetType(ControlLoopTargetType.VNF);
386 event.setClosedLoopAlarmStart(Instant.now());
387 event.setAai(new HashMap<>());
389 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
390 event.getAai().put("generic-vnf.prov-status", "ACTIVE");
391 event.getAai().put("generic-vnf.vnf-id", "notused");
393 event.getAai().put("generic-vnf.vnf-id", "getFail");
395 event.setClosedLoopEventStatus(status);
396 StringBuilder sb = new StringBuilder();
397 sb.append("{ \"Configurations\":[ { \"data\":{ \"FAPService\":"
398 + " { \"alias\":\"Cell1\", \"X0005b9Lte\" : { \"PhyCellIdInUse\" :"
399 + " \"35\", \"PnfName\" : \"cu1\" }, \"CellConfig\":{ \"LTE\":{ \"RAN\":"
400 + "{ \"Common\":{ \"CellIdentity\":\"1\" } } } } } } } ] }");
402 event.setPayload(sb.toString());
403 logger.debug("\n============ Policy receiving ONSET event !!! ===========\n");
404 logger.debug("\n============ event ===========\n {}", event);
405 kieSession.insert(event);
409 * This method will dump all the facts in the working memory.
412 * the session containing the facts
414 public void dumpFacts(KieSession kieSession) {
415 logger.debug("Fact Count: {}", kieSession.getFactCount());
416 for (FactHandle handle : kieSession.getFactHandles()) {
417 logger.debug("FACT: {}", handle);