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();
169 // allow object clean-up
170 kieSession.fireAllRules();
173 * The only fact in memory should be Params
175 assertEquals(1, kieSession.getFactCount());
178 * Print what's left in memory
180 dumpFacts(kieSession);
185 public void aaiGetFailTest() {
188 * Allows the PolicyEngine to callback to this object to notify that there is an
189 * event ready to be pulled from the queue
191 for (TopicSink sink : noopTopics) {
192 assertTrue(sink.start());
197 * Create a unique requestId
199 requestId = UUID.randomUUID();
202 * Simulate an onset event the policy engine will receive from DCAE to kick off
203 * processing through the rules
205 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, false);
207 kieSession.fireUntilHalt();
209 // allow object clean-up
210 kieSession.fireAllRules();
213 * The only fact in memory should be Params
215 assertEquals(1, kieSession.getFactCount());
218 * Print what's left in memory
220 dumpFacts(kieSession);
225 * This method will start a kie session and instantiate the Policy Engine.
227 * @param droolsTemplate
230 * the yaml file containing the policies
235 * @param policyVersion
236 * version of the policy
237 * @return the kieSession to be used to insert facts
238 * @throws IOException
241 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
242 String policyName, String policyVersion) throws IOException {
245 * Load policies from yaml
247 pair = Util.loadYaml(yamlFile);
249 assertNotNull(pair.first);
250 assertNotNull(pair.first.getControlLoop());
251 assertNotNull(pair.first.getControlLoop().getControlLoopName());
252 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
255 * Construct a kie session
257 final KieSession kieSession = Util.buildContainer(droolsTemplate,
258 pair.first.getControlLoop().getControlLoopName(), policyScope, policyName, policyVersion,
259 URLEncoder.encode(pair.second, "UTF-8"));
262 * Retrieve the Policy Engine
265 logger.debug("======controlloop======");
266 logger.debug(((ControlLoopPolicy) pair.first).toString());
267 logger.debug("======policies======");
268 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
269 logger.debug("============");
278 * org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.
282 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
283 logger.debug("\n============ onTopicEvent!!! ===========\n");
284 logger.debug("topic: {}, event: {}", topic, event);
286 * Pull the object that was sent out to DMAAP and make sure it is a
287 * ControlLoopNoticiation of type active
290 if ("POLICY-CL-MGT".equals(topic)) {
291 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
292 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
293 } else if ("SDNR-CL".equals(topic)) {
294 obj = org.onap.policy.sdnr.util.Serialization.gsonJunit.fromJson(event,
295 org.onap.policy.sdnr.PciRequestWrapper.class);
298 if (obj instanceof VirtualControlLoopNotification) {
299 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
300 String policyName = notification.getPolicyName();
301 logger.debug("Rule Fired: {}", policyName);
302 if (policyName.endsWith("EVENT")) {
303 assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
304 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
305 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
306 assertNotNull(notification.getMessage());
307 assertTrue(notification.getMessage().startsWith("Sending guard query"));
308 } else if (policyName.endsWith("GUARD.RESPONSE")) {
309 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
310 assertNotNull(notification.getMessage());
311 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
312 } else if (policyName.endsWith("GUARD_PERMITTED")) {
313 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
314 assertNotNull(notification.getMessage());
315 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
316 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
318 logger.debug("The operation timed out");
319 fail("Operation Timed Out");
320 } else if (policyName.endsWith("SDNR.RESPONSE")) {
321 assertEquals(ControlLoopNotificationType.OPERATION_SUCCESS, notification.getNotification());
322 assertNotNull(notification.getMessage());
323 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
324 } else if (policyName.endsWith("EVENT.MANAGER")) {
325 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-id"))) {
326 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
329 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
332 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
334 logger.debug("The control loop timed out");
335 fail("Control Loop Timed Out");
337 } else if (obj instanceof PciRequestWrapper) {
339 * The request should be of type PciRequestWrapper and the subrequestid should
342 PciRequestWrapper dmaapRequest = (PciRequestWrapper) obj;
343 PciRequest pciRequest = dmaapRequest.getBody();
344 assertEquals("1", pciRequest.getCommonHeader().getSubRequestId());
346 logger.debug("\n============ SDNR received the request!!! ===========\n");
347 logger.debug("\n============ dmaapRequest ===========\n {} ", dmaapRequest);
348 logger.debug("\n============ pciRequest ===========\n {}", pciRequest);
351 * Simulate a success response from SDNR and insert the response into the
354 PciResponse pciResponse = new PciResponse(pciRequest);
355 pciResponse.getStatus().setCode(200);
356 pciResponse.getStatus().setValue("SUCCESS");
357 StringBuilder sb = new StringBuilder();
358 sb.append("{ \"Configurations\":[ { \"Status\": { \"Code\": 200, \"Value\":"
359 + " \"SUCCESS\" }, \"data\":{ \"FAPService\":{ \"alias\":"
360 + "\"Network1\", \"X0005b9Lte\" : { \"PnfName\" : \"cu1\" }, \"CellConfig\":"
361 + "{ \"LTE\":{ \"RAN\":{ \"Common\":{ \"CellIdentity\":" + "\"1\" } } } } } } } ] }");
363 pciResponse.setPayload(sb.toString());
364 PciResponseWrapper dmaapResponse = new PciResponseWrapper();
365 dmaapResponse.setBody(pciResponse);
366 dmaapResponse.setType("response");
367 logger.debug("\n============ SDNR sending response!!! ===========\n");
368 logger.debug("\n============ dmaapResponse ===========\n {}", dmaapResponse);
369 logger.debug("\n============ pciResponse ===========\n {}", pciResponse);
370 kieSession.insert(dmaapResponse);
375 * This method is used to simulate event messages from DCAE that start the
376 * control loop (onset message).
379 * the controlLoopName comes from the policy
381 * the requestId for this event
385 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
386 boolean isEnriched) {
387 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
388 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
389 event.setRequestId(requestId);
390 event.setTarget("generic-vnf.vnf-id");
391 event.setTargetType(ControlLoopTargetType.VNF);
392 event.setClosedLoopAlarmStart(Instant.now());
393 event.setAai(new HashMap<>());
395 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
396 event.getAai().put("generic-vnf.prov-status", "ACTIVE");
397 event.getAai().put("generic-vnf.vnf-id", "notused");
399 event.getAai().put("generic-vnf.vnf-id", "getFail");
401 event.setClosedLoopEventStatus(status);
402 StringBuilder sb = new StringBuilder();
403 sb.append("{ \"Configurations\":[ { \"data\":{ \"FAPService\":"
404 + " { \"alias\":\"Cell1\", \"X0005b9Lte\" : { \"PhyCellIdInUse\" :"
405 + " \"35\", \"PnfName\" : \"cu1\" }, \"CellConfig\":{ \"LTE\":{ \"RAN\":"
406 + "{ \"Common\":{ \"CellIdentity\":\"1\" } } } } } } } ] }");
408 event.setPayload(sb.toString());
409 logger.debug("\n============ Policy receiving ONSET event !!! ===========\n");
410 logger.debug("\n============ event ===========\n {}", event);
411 kieSession.insert(event);
415 * This method will dump all the facts in the working memory.
418 * the session containing the facts
420 public void dumpFacts(KieSession kieSession) {
421 logger.debug("Fact Count: {}", kieSession.getFactCount());
422 for (FactHandle handle : kieSession.getFactHandles()) {
423 logger.debug("FACT: {}", handle);