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.PolicyEngine;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public class VCPEControlLoopTest implements TopicListener {
61 private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
63 private static List<? extends TopicSink> noopTopics;
65 private static KieSession kieSession;
66 private static Util.Pair<ControlLoopPolicy, String> pair;
67 private UUID requestID;
70 /* Set environment properties */
77 public static void setUpSimulator() {
78 PolicyEngine.manager.configure(new Properties());
79 assertTrue(PolicyEngine.manager.start());
80 Properties noopSinkProperties = new Properties();
81 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
82 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LCMRequestWrapper");
83 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", "org.onap.policy.appclcm.util.Serialization,gson");
84 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
85 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
86 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
88 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
89 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", "org.onap.policy.appclcm.LCMRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
93 } catch (Exception e) {
97 * Start the kie session
100 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
101 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
102 "service=ServiceDemo;resource=Res1Demo;type=operational",
104 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
105 } catch (IOException e) {
107 logger.debug("Could not create kieSession");
108 fail("Could not create kieSession");
113 public static void tearDownSimulator() {
115 * Gracefully shut down the kie session
117 kieSession.dispose();
119 HttpServletServer.factory.destroy();
120 PolicyEngine.manager.shutdown();
121 TopicEndpoint.manager.shutdown();
122 PolicyEngine.manager.stop();
126 public void successTest() {
129 * Allows the PolicyEngine to callback to this object to
130 * notify that there is an event ready to be pulled
133 for (TopicSink sink : noopTopics) {
134 assertTrue(sink.start());
139 * Create a unique requestId
141 requestID = UUID.randomUUID();
144 * Simulate an onset event the policy engine will
145 * receive from DCAE to kick off processing through
148 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
151 kieSession.fireUntilHalt();
154 * The only fact in memory should be Params
156 assertEquals(1, kieSession.getFactCount());
159 * Print what's left in memory
161 dumpFacts(kieSession);
165 public void aaiGetFailTest() {
168 * Allows the PolicyEngine to callback to this object to
169 * notify that there is an event ready to be pulled
172 for (TopicSink sink : noopTopics) {
173 assertTrue(sink.start());
178 * Create a unique requestId
180 requestID = UUID.randomUUID();
183 * Simulate an onset event the policy engine will
184 * receive from DCAE to kick off processing through
187 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
190 kieSession.fireUntilHalt();
193 * The only fact in memory should be Params
195 assertEquals(1, kieSession.getFactCount());
198 * Print what's left in memory
200 dumpFacts(kieSession);
205 * This method will start a kie session and instantiate
208 * @param droolsTemplate
211 * the yaml file containing the policies
216 * @param policyVersion
217 * version of the policy
218 * @return the kieSession to be used to insert facts
219 * @throws IOException
221 private static KieSession startSession(String droolsTemplate,
225 String policyVersion) throws IOException {
228 * Load policies from yaml
230 pair = Util.loadYaml(yamlFile);
232 assertNotNull(pair.a);
233 assertNotNull(pair.a.getControlLoop());
234 assertNotNull(pair.a.getControlLoop().getControlLoopName());
235 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
238 * Construct a kie session
240 final KieSession kieSession = Util.buildContainer(droolsTemplate,
241 pair.a.getControlLoop().getControlLoopName(),
245 URLEncoder.encode(pair.b, "UTF-8"));
248 * Retrieve the Policy Engine
251 logger.debug("============");
252 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
253 logger.debug("============");
260 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
262 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
264 * Pull the object that was sent out to DMAAP and make
265 * sure it is a ControlLoopNoticiation of type active
268 if ("POLICY-CL-MGT".equals(topic)) {
269 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
271 else if ("APPC-LCM-READ".equals(topic))
272 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
274 if (obj instanceof VirtualControlLoopNotification) {
275 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
276 String policyName = notification.policyName;
277 if (policyName.endsWith("EVENT")) {
278 logger.debug("Rule Fired: " + notification.policyName);
279 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-id"))) {
280 assertEquals(ControlLoopNotificationType.REJECTED, notification.notification);
284 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
287 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
288 logger.debug("Rule Fired: " + notification.policyName);
289 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
290 assertNotNull(notification.message);
291 assertTrue(notification.message.startsWith("Sending guard query"));
293 else if (policyName.endsWith("GUARD.RESPONSE")) {
294 logger.debug("Rule Fired: " + notification.policyName);
295 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
296 assertNotNull(notification.message);
297 assertTrue(notification.message.toLowerCase().endsWith("permit"));
299 else if (policyName.endsWith("GUARD_PERMITTED")) {
300 logger.debug("Rule Fired: " + notification.policyName);
301 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
302 assertNotNull(notification.message);
303 assertTrue(notification.message.startsWith("actor=APPC"));
305 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
306 logger.debug("Rule Fired: " + notification.policyName);
308 logger.debug("The operation timed out");
309 fail("Operation Timed Out");
311 else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
312 logger.debug("Rule Fired: " + notification.policyName);
313 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
314 assertNotNull(notification.message);
315 assertTrue(notification.message.startsWith("actor=APPC"));
316 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
318 else if (policyName.endsWith("EVENT.MANAGER")) {
319 logger.debug("Rule Fired: " + notification.policyName);
320 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
323 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
324 logger.debug("Rule Fired: " + notification.policyName);
326 logger.debug("The control loop timed out");
327 fail("Control Loop Timed Out");
330 else if (obj instanceof LCMRequestWrapper) {
332 * The request should be of type LCMRequestWrapper
333 * and the subrequestid should be 1
335 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
336 LCMRequest appcRequest = dmaapRequest.getBody();
337 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
339 logger.debug("\n============ APPC received the request!!! ===========\n");
342 * Simulate a success response from APPC and insert
343 * the response into the working memory
345 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
346 LCMResponse appcResponse = new LCMResponse(appcRequest);
347 appcResponse.getStatus().setCode(400);
348 appcResponse.getStatus().setMessage("AppC success");
349 dmaapResponse.setBody(appcResponse);
350 kieSession.insert(dmaapResponse);
355 * This method is used to simulate event messages from DCAE
356 * that start the control loop (onset message) or end the
357 * control loop (abatement message).
359 * @param policy the controlLoopName comes from the policy
360 * @param requestID the requestId for this event
361 * @param status could be onset or abated
363 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
364 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
365 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
366 event.requestID = requestID;
367 event.target = "generic-vnf.vnf-id";
368 event.closedLoopAlarmStart = Instant.now();
369 event.AAI = new HashMap<>();
370 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
371 event.closedLoopEventStatus = status;
372 kieSession.insert(event);
375 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfId) {
376 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
377 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
378 event.requestID = requestID;
379 event.target = "generic-vnf.vnf-id";
380 event.closedLoopAlarmStart = Instant.now();
381 event.AAI = new HashMap<>();
382 event.AAI.put("generic-vnf.vnf-id", vnfId);
383 event.closedLoopEventStatus = status;
384 kieSession.insert(event);
388 * This method will dump all the facts in the working memory.
390 * @param kieSession the session containing the facts
392 public void dumpFacts(KieSession kieSession) {
393 logger.debug("Fact Count: {}", kieSession.getFactCount());
394 for (FactHandle handle : kieSession.getFactHandles()) {
395 logger.debug("FACT: {}", handle);