2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T 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.*;
25 import java.io.IOException;
26 import java.net.URLEncoder;
27 import java.time.Instant;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Properties;
31 import java.util.UUID;
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.kie.api.runtime.KieSession;
37 import org.kie.api.runtime.rule.FactHandle;
38 import org.onap.policy.appclcm.LCMRequest;
39 import org.onap.policy.appclcm.LCMRequestWrapper;
40 import org.onap.policy.appclcm.LCMResponse;
41 import org.onap.policy.appclcm.LCMResponseWrapper;
42 import org.onap.policy.controlloop.ControlLoopEventStatus;
43 import org.onap.policy.controlloop.ControlLoopNotificationType;
44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
45 import org.onap.policy.controlloop.VirtualControlLoopNotification;
46 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
47 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
48 import org.onap.policy.drools.event.comm.TopicEndpoint;
49 import org.onap.policy.drools.event.comm.TopicListener;
50 import org.onap.policy.drools.event.comm.TopicSink;
51 import org.onap.policy.drools.http.server.HttpServletServer;
52 import org.onap.policy.drools.properties.PolicyProperties;
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.LoggerUtil;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 public class VCPEControlLoopTest implements TopicListener {
63 private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
65 private static List<? extends TopicSink> noopTopics;
67 private static KieSession kieSession;
68 private static Util.Pair<ControlLoopPolicy, String> pair;
69 private UUID requestID;
72 /* Set environment properties */
76 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
80 public static void setUpSimulator() {
81 PolicyEngine.manager.configure(new Properties());
82 assertTrue(PolicyEngine.manager.start());
83 Properties noopSinkProperties = new Properties();
84 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
85 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LCMRequestWrapper");
86 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", "org.onap.policy.appclcm.util.Serialization,gson");
87 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
88 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
89 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
91 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
92 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", "org.onap.policy.appclcm.LCMRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
96 } catch (Exception e) {
100 * Start the kie session
103 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
104 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
105 "service=ServiceDemo;resource=Res1Demo;type=operational",
107 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
108 } catch (IOException e) {
110 logger.debug("Could not create kieSession");
111 fail("Could not create kieSession");
116 public static void tearDownSimulator() {
118 * Gracefully shut down the kie session
120 kieSession.dispose();
122 PolicyEngine.manager.stop();
123 HttpServletServer.factory.destroy();
124 PolicyController.factory.shutdown();
125 TopicEndpoint.manager.shutdown();
129 public void successTest() {
132 * Allows the PolicyEngine to callback to this object to
133 * notify that there is an event ready to be pulled
136 for (TopicSink sink : noopTopics) {
137 assertTrue(sink.start());
142 * Create a unique requestId
144 requestID = UUID.randomUUID();
147 * Simulate an onset event the policy engine will
148 * receive from DCAE to kick off processing through
151 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
154 kieSession.fireUntilHalt();
157 * The only fact in memory should be Params
159 assertEquals(1, kieSession.getFactCount());
162 * Print what's left in memory
164 dumpFacts(kieSession);
168 public void aaiGetFailTest() {
171 * Allows the PolicyEngine to callback to this object to
172 * notify that there is an event ready to be pulled
175 for (TopicSink sink : noopTopics) {
176 assertTrue(sink.start());
181 * Create a unique requestId
183 requestID = UUID.randomUUID();
186 * Simulate an onset event the policy engine will
187 * receive from DCAE to kick off processing through
190 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
193 kieSession.fireUntilHalt();
196 * The only fact in memory should be Params
198 assertEquals(1, kieSession.getFactCount());
201 * Print what's left in memory
203 dumpFacts(kieSession);
208 * This method will start a kie session and instantiate
211 * @param droolsTemplate
214 * the yaml file containing the policies
219 * @param policyVersion
220 * version of the policy
221 * @return the kieSession to be used to insert facts
222 * @throws IOException
224 private static KieSession startSession(String droolsTemplate,
228 String policyVersion) throws IOException {
231 * Load policies from yaml
233 pair = Util.loadYaml(yamlFile);
235 assertNotNull(pair.a);
236 assertNotNull(pair.a.getControlLoop());
237 assertNotNull(pair.a.getControlLoop().getControlLoopName());
238 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
241 * Construct a kie session
243 final KieSession kieSession = Util.buildContainer(droolsTemplate,
244 pair.a.getControlLoop().getControlLoopName(),
248 URLEncoder.encode(pair.b, "UTF-8"));
251 * Retrieve the Policy Engine
254 logger.debug("============");
255 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
256 logger.debug("============");
263 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
265 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
267 * Pull the object that was sent out to DMAAP and make
268 * sure it is a ControlLoopNoticiation of type active
271 if ("POLICY-CL-MGT".equals(topic)) {
272 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
274 else if ("APPC-LCM-READ".equals(topic))
275 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
277 if (obj instanceof VirtualControlLoopNotification) {
278 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
279 String policyName = notification.policyName;
280 if (policyName.endsWith("EVENT")) {
281 logger.debug("Rule Fired: " + notification.policyName);
282 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
284 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
285 logger.debug("Rule Fired: " + notification.policyName);
286 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
287 assertNotNull(notification.message);
288 assertTrue(notification.message.startsWith("Sending guard query"));
290 else if (policyName.endsWith("GUARD.RESPONSE")) {
291 logger.debug("Rule Fired: " + notification.policyName);
292 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
293 assertNotNull(notification.message);
294 assertTrue(notification.message.toLowerCase().endsWith("permit"));
296 else if (policyName.endsWith("GUARD_PERMITTED")) {
297 logger.debug("Rule Fired: " + notification.policyName);
298 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
299 assertNotNull(notification.message);
300 assertTrue(notification.message.startsWith("actor=APPC"));
302 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
303 logger.debug("Rule Fired: " + notification.policyName);
305 logger.debug("The operation timed out");
306 fail("Operation Timed Out");
308 else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
309 logger.debug("Rule Fired: " + notification.policyName);
310 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
311 assertNotNull(notification.message);
312 assertTrue(notification.message.startsWith("actor=APPC"));
313 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
315 else if (policyName.endsWith("EVENT.MANAGER")) {
316 logger.debug("Rule Fired: " + notification.policyName);
317 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
318 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
322 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
326 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
327 logger.debug("Rule Fired: " + notification.policyName);
329 logger.debug("The control loop timed out");
330 fail("Control Loop Timed Out");
333 else if (obj instanceof LCMRequestWrapper) {
335 * The request should be of type LCMRequestWrapper
336 * and the subrequestid should be 1
338 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
339 LCMRequest appcRequest = dmaapRequest.getBody();
340 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
341 assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
343 logger.debug("\n============ APPC received the request!!! ===========\n");
346 * Simulate a success response from APPC and insert
347 * the response into the working memory
349 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
350 LCMResponse appcResponse = new LCMResponse(appcRequest);
351 appcResponse.getStatus().setCode(400);
352 appcResponse.getStatus().setMessage("AppC success");
353 dmaapResponse.setBody(appcResponse);
354 kieSession.insert(dmaapResponse);
359 * This method is used to simulate event messages from DCAE
360 * that start the control loop (onset message) or end the
361 * control loop (abatement message).
363 * @param policy the controlLoopName comes from the policy
364 * @param requestID the requestId for this event
365 * @param status could be onset or abated
367 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
368 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
369 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
370 event.requestID = requestID;
371 event.target = "generic-vnf.vnf-name";
372 event.closedLoopAlarmStart = Instant.now();
373 event.AAI = new HashMap<>();
374 event.AAI.put("generic-vnf.vnf-name", "testGenericVnfName");
375 event.closedLoopEventStatus = status;
376 kieSession.insert(event);
379 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfName) {
380 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
381 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
382 event.requestID = requestID;
383 event.target = "generic-vnf.vnf-name";
384 event.closedLoopAlarmStart = Instant.now();
385 event.AAI = new HashMap<>();
386 event.AAI.put("generic-vnf.vnf-name", vnfName);
387 event.closedLoopEventStatus = status;
388 kieSession.insert(event);
392 * This method will dump all the facts in the working memory.
394 * @param kieSession the session containing the facts
396 public void dumpFacts(KieSession kieSession) {
397 logger.debug("Fact Count: {}", kieSession.getFactCount());
398 for (FactHandle handle : kieSession.getFactHandles()) {
399 logger.debug("FACT: {}", handle);