2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.template.demo;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
28 import java.io.IOException;
29 import java.net.URLEncoder;
30 import java.time.Instant;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Properties;
34 import java.util.UUID;
36 import org.junit.AfterClass;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.kie.api.runtime.KieSession;
40 import org.kie.api.runtime.rule.FactHandle;
41 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
42 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
43 import org.onap.policy.common.endpoints.event.comm.TopicListener;
44 import org.onap.policy.common.endpoints.event.comm.TopicSink;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
46 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
47 import org.onap.policy.controlloop.ControlLoopEventStatus;
48 import org.onap.policy.controlloop.ControlLoopNotificationType;
49 import org.onap.policy.controlloop.ControlLoopTargetType;
50 import org.onap.policy.controlloop.VirtualControlLoopEvent;
51 import org.onap.policy.controlloop.VirtualControlLoopNotification;
52 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyController;
56 import org.onap.policy.drools.system.PolicyEngine;
57 import org.onap.policy.drools.utils.logging.LoggerUtil;
58 import org.onap.policy.sdnr.PciRequest;
59 import org.onap.policy.sdnr.PciRequestWrapper;
60 import org.onap.policy.sdnr.PciResponse;
61 import org.onap.policy.sdnr.PciResponseWrapper;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 public class VpciControlLoopTest implements TopicListener {
67 private static final Logger logger = LoggerFactory.getLogger(VpciControlLoopTest.class);
69 private static List<? extends TopicSink> noopTopics;
71 private static KieSession kieSession;
72 private static Util.Pair<ControlLoopPolicy, String> pair;
73 private UUID requestId;
76 /* Set environment properties */
80 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "DEBUG");
84 * Setup the simulator.
87 public static void setUpSimulator() {
88 PolicyEngine.manager.configure(new Properties());
89 assertTrue(PolicyEngine.manager.start());
90 Properties noopSinkProperties = new Properties();
91 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "SDNR-CL,POLICY-CL-MGT");
92 noopSinkProperties.put("noop.sink.topics.SDNR-CL.events", "org.onap.policy.sdnr.PciRequestWrapper");
93 noopSinkProperties.put("noop.sink.topics.SDNR-CL.events.custom.gson",
94 "org.onap.policy.sdnr.util.Serialization,gson");
95 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
96 "org.onap.policy.controlloop.VirtualControlLoopNotification");
97 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
98 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
99 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
101 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
102 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
104 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "SDNR-CL",
105 "org.onap.policy.sdnr.PciRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
108 Util.buildGuardSim();
109 } catch (Exception e) {
110 fail(e.getMessage());
113 * Start the kie session
116 kieSession = startSession(
117 "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
118 + "/src/main/resources/__closedLoopControlName__.drl",
119 "src/test/resources/yaml/policy_ControlLoop_vPCI.yaml", "type=operational", "CL_vPCI", "v3.0.0");
120 } catch (IOException e) {
122 logger.debug("Could not create kieSession");
123 fail("Could not create kieSession");
128 * Tear down the simulator.
131 public static void tearDownSimulator() {
133 * Gracefully shut down the kie session
135 kieSession.dispose();
137 PolicyEngine.manager.stop();
138 HttpServletServer.factory.destroy();
139 PolicyController.factory.shutdown();
140 TopicEndpoint.manager.shutdown();
144 public void successTest() {
147 * Allows the PolicyEngine to callback to this object to notify that there is an
148 * event ready to be pulled from the queue
150 for (TopicSink sink : noopTopics) {
151 assertTrue(sink.start());
156 * Create a unique requestId
158 requestId = UUID.randomUUID();
161 * Simulate an onset event the policy engine will receive from DCAE to kick off
162 * processing through the rules
164 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, true);
166 kieSession.fireUntilHalt();
169 * The only fact in memory should be Params
171 assertEquals(1, kieSession.getFactCount());
174 * Print what's left in memory
176 dumpFacts(kieSession);
181 public void aaiGetFailTest() {
184 * Allows the PolicyEngine to callback to this object to notify that there is an
185 * event ready to be pulled from the queue
187 for (TopicSink sink : noopTopics) {
188 assertTrue(sink.start());
193 * Create a unique requestId
195 requestId = UUID.randomUUID();
198 * Simulate an onset event the policy engine will receive from DCAE to kick off
199 * processing through the rules
201 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, false);
203 kieSession.fireUntilHalt();
206 * The only fact in memory should be Params
208 assertEquals(1, kieSession.getFactCount());
211 * Print what's left in memory
213 dumpFacts(kieSession);
218 * This method will start a kie session and instantiate the Policy Engine.
220 * @param droolsTemplate
223 * the yaml file containing the policies
228 * @param policyVersion
229 * version of the policy
230 * @return the kieSession to be used to insert facts
231 * @throws IOException
234 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
235 String policyName, String policyVersion) throws IOException {
238 * Load policies from yaml
240 pair = Util.loadYaml(yamlFile);
242 assertNotNull(pair.first);
243 assertNotNull(pair.first.getControlLoop());
244 assertNotNull(pair.first.getControlLoop().getControlLoopName());
245 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
248 * Construct a kie session
250 final KieSession kieSession = Util.buildContainer(droolsTemplate,
251 pair.first.getControlLoop().getControlLoopName(), policyScope, policyName, policyVersion,
252 URLEncoder.encode(pair.second, "UTF-8"));
255 * Retrieve the Policy Engine
258 logger.debug("======controlloop======");
259 logger.debug(((ControlLoopPolicy) pair.first).toString());
260 logger.debug("======policies======");
261 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
262 logger.debug("============");
271 * org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.
275 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
276 logger.debug("\n============ onTopicEvent!!! ===========\n");
277 logger.debug("topic: {}, event: {}", topic, event);
279 * Pull the object that was sent out to DMAAP and make sure it is a
280 * ControlLoopNoticiation of type active
283 if ("POLICY-CL-MGT".equals(topic)) {
284 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
285 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
286 } else if ("SDNR-CL".equals(topic)) {
287 obj = org.onap.policy.sdnr.util.Serialization.gsonJunit.fromJson(event,
288 org.onap.policy.sdnr.PciRequestWrapper.class);
291 if (obj instanceof VirtualControlLoopNotification) {
292 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
293 String policyName = notification.getPolicyName();
294 logger.debug("Rule Fired: {}", policyName);
295 if (policyName.endsWith("EVENT")) {
296 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
297 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
298 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
299 assertNotNull(notification.getMessage());
300 assertTrue(notification.getMessage().startsWith("Sending guard query"));
301 } else if (policyName.endsWith("GUARD.RESPONSE")) {
302 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
303 assertNotNull(notification.getMessage());
304 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
305 } else if (policyName.endsWith("GUARD_PERMITTED")) {
306 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
307 assertNotNull(notification.getMessage());
308 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
309 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
311 logger.debug("The operation timed out");
312 fail("Operation Timed Out");
313 } else if (policyName.endsWith("SDNR.RESPONSE")) {
314 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
315 assertNotNull(notification.getMessage());
316 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
317 } else if (policyName.endsWith("EVENT.MANAGER")) {
318 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-id"))) {
319 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
322 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
325 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
327 logger.debug("The control loop timed out");
328 fail("Control Loop Timed Out");
330 } else if (obj instanceof PciRequestWrapper) {
332 * The request should be of type PciRequestWrapper and the subrequestid should
335 PciRequestWrapper dmaapRequest = (PciRequestWrapper) obj;
336 PciRequest pciRequest = dmaapRequest.getBody();
337 assertTrue(pciRequest.getCommonHeader().getSubRequestId().equals("1"));
339 logger.debug("\n============ SDNR received the request!!! ===========\n");
340 logger.debug("\n============ dmaapRequest ===========\n {} ", dmaapRequest);
341 logger.debug("\n============ pciRequest ===========\n {}", pciRequest);
344 * Simulate a success response from SDNR and insert the response into the
347 PciResponse pciResponse = new PciResponse(pciRequest);
348 pciResponse.getStatus().setCode(200);
349 pciResponse.getStatus().setValue("SUCCESS");
350 StringBuilder sb = new StringBuilder();
351 sb.append("{ \"Configurations\":[ { \"Status\": { \"Code\": 200, \"Value\":"
352 + " \"SUCCESS\" }, \"data\":{ \"FAPService\":{ \"alias\":"
353 + "\"Network1\", \"X0005b9Lte\" : { \"PnfName\" : \"cu1\" }, \"CellConfig\":"
354 + "{ \"LTE\":{ \"RAN\":{ \"Common\":{ \"CellIdentity\":" + "\"1\" } } } } } } } ] }");
356 pciResponse.setPayload(sb.toString());
357 PciResponseWrapper dmaapResponse = new PciResponseWrapper();
358 dmaapResponse.setBody(pciResponse);
359 dmaapResponse.setType("response");
360 logger.debug("\n============ SDNR sending response!!! ===========\n");
361 logger.debug("\n============ dmaapResponse ===========\n {}", dmaapResponse);
362 logger.debug("\n============ pciResponse ===========\n {}", pciResponse);
363 kieSession.insert(dmaapResponse);
368 * This method is used to simulate event messages from DCAE that start the
369 * control loop (onset message).
372 * the controlLoopName comes from the policy
374 * the requestId for this event
378 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
379 boolean isEnriched) {
380 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
381 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
382 event.setRequestId(requestId);
383 event.setTarget("generic-vnf.vnf-id");
384 event.setTargetType(ControlLoopTargetType.VNF);
385 event.setClosedLoopAlarmStart(Instant.now());
386 event.setAai(new HashMap<>());
388 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
389 event.getAai().put("generic-vnf.prov-status", "ACTIVE");
390 event.getAai().put("generic-vnf.vnf-id", "notused");
392 event.getAai().put("generic-vnf.vnf-id", "getFail");
394 event.setClosedLoopEventStatus(status);
395 StringBuilder sb = new StringBuilder();
396 sb.append("{ \"Configurations\":[ { \"data\":{ \"FAPService\":"
397 + " { \"alias\":\"Cell1\", \"X0005b9Lte\" : { \"PhyCellIdInUse\" :"
398 + " \"35\", \"PnfName\" : \"cu1\" }, \"CellConfig\":{ \"LTE\":{ \"RAN\":"
399 + "{ \"Common\":{ \"CellIdentity\":\"1\" } } } } } } } ] }");
401 event.setPayload(sb.toString());
402 logger.debug("\n============ Policy receiving ONSET event !!! ===========\n");
403 logger.debug("\n============ event ===========\n {}", event);
404 kieSession.insert(event);
408 * This method will dump all the facts in the working memory.
411 * the session containing the facts
413 public void dumpFacts(KieSession kieSession) {
414 logger.debug("Fact Count: {}", kieSession.getFactCount());
415 for (FactHandle handle : kieSession.getFactHandles()) {
416 logger.debug("FACT: {}", handle);