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.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.appc.Request;
42 import org.onap.policy.appc.Response;
43 import org.onap.policy.appc.ResponseCode;
44 import org.onap.policy.controlloop.ControlLoopEventStatus;
45 import org.onap.policy.controlloop.ControlLoopNotificationType;
46 import org.onap.policy.controlloop.VirtualControlLoopEvent;
47 import org.onap.policy.controlloop.VirtualControlLoopNotification;
48 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
49 import org.onap.policy.drools.event.comm.TopicEndpoint;
50 import org.onap.policy.drools.event.comm.TopicListener;
51 import org.onap.policy.drools.event.comm.TopicSink;
52 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
53 import org.onap.policy.drools.http.server.HttpServletServer;
54 import org.onap.policy.drools.properties.PolicyProperties;
55 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
56 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
57 import org.onap.policy.drools.system.PolicyController;
58 import org.onap.policy.drools.system.PolicyEngine;
59 import org.onap.policy.drools.utils.LoggerUtil;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public class VFWControlLoopTest implements TopicListener {
65 private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
67 private static List<? extends TopicSink> noopTopics;
69 private static KieSession kieSession;
70 private static Util.Pair<ControlLoopPolicy, String> pair;
71 private UUID requestID;
74 /* Set environment properties */
78 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
82 public static void setUpSimulator() {
83 PolicyEngine.manager.configure(new Properties());
84 assertTrue(PolicyEngine.manager.start());
85 Properties noopSinkProperties = new Properties();
86 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
87 noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
88 noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", "org.onap.policy.appc.util.Serialization,gsonPretty");
89 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
90 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
91 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
93 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
94 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111);
99 } catch (Exception e) {
100 fail(e.getMessage());
104 * Start the kie session
107 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
108 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
109 "service=ServiceDemo;resource=Res1Demo;type=operational",
111 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
112 } catch (IOException e) {
114 logger.debug("Could not create kieSession");
115 fail("Could not create kieSession");
120 public static void tearDownSimulator() {
122 * Gracefully shut down the kie session
124 kieSession.dispose();
126 PolicyEngine.manager.stop();
127 HttpServletServer.factory.destroy();
128 PolicyController.factory.shutdown();
129 TopicEndpoint.manager.shutdown();
133 public void successTest() {
136 * Allows the PolicyEngine to callback to this object to
137 * notify that there is an event ready to be pulled
140 for (TopicSink sink : noopTopics) {
141 assertTrue(sink.start());
146 * Create a unique requestId
148 requestID = UUID.randomUUID();
151 * Simulate an onset event the policy engine will
152 * receive from DCAE to kick off processing through
155 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
158 kieSession.fireUntilHalt();
160 catch (Exception e) {
162 logger.warn(e.toString());
168 * The only fact in memory should be Params
170 assertEquals(1, kieSession.getFactCount());
173 * Print what's left in memory
175 dumpFacts(kieSession);
179 public void aaiFailTests() {
182 * Allows the PolicyEngine to callback to this object to
183 * notify that there is an event ready to be pulled
186 for (TopicSink sink : noopTopics) {
187 assertTrue(sink.start());
192 * Create a unique requestId
194 requestID = UUID.randomUUID();
197 * Simulate an onset event the policy engine will
198 * receive from DCAE to kick off processing through
201 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error");
203 kieSession.fireUntilHalt();
205 catch (Exception e) {
207 logger.warn(e.toString());
208 fail(e.getMessage());
212 * The only fact in memory should be Params
214 assertEquals(1, kieSession.getFactCount());
217 * Print what's left in memory
219 dumpFacts(kieSession);
222 * Create a unique requestId
224 requestID = UUID.randomUUID();
227 * Simulate an onset event the policy engine will
228 * receive from DCAE to kick off processing through
232 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
235 kieSession.fireUntilHalt();
237 catch (Exception e) {
239 logger.warn(e.toString());
240 fail(e.getMessage());
244 * The only fact in memory should be Params
246 assertEquals(1, kieSession.getFactCount());
249 * Print what's left in memory
251 dumpFacts(kieSession);
255 * This method will start a kie session and instantiate
258 * @param droolsTemplate
261 * the yaml file containing the policies
266 * @param policyVersion
267 * version of the policy
268 * @return the kieSession to be used to insert facts
269 * @throws IOException
271 private static KieSession startSession(String droolsTemplate,
275 String policyVersion) throws IOException {
278 * Load policies from yaml
280 pair = Util.loadYaml(yamlFile);
282 assertNotNull(pair.a);
283 assertNotNull(pair.a.getControlLoop());
284 assertNotNull(pair.a.getControlLoop().getControlLoopName());
285 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
288 * Construct a kie session
290 final KieSession kieSession = Util.buildContainer(droolsTemplate,
291 pair.a.getControlLoop().getControlLoopName(),
295 URLEncoder.encode(pair.b, "UTF-8"));
298 * Retrieve the Policy Engine
301 logger.debug("============");
302 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
303 logger.debug("============");
309 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
311 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
313 * Pull the object that was sent out to DMAAP and make
314 * sure it is a ControlLoopNoticiation of type active
317 if ("POLICY-CL-MGT".equals(topic)) {
318 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
320 else if ("APPC-CL".equals(topic))
321 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, org.onap.policy.appc.Request.class);
323 if (obj instanceof VirtualControlLoopNotification) {
324 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
325 String policyName = notification.policyName;
326 if (policyName.endsWith("EVENT")) {
327 logger.debug("Rule Fired: " + notification.policyName);
328 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
330 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
331 logger.debug("Rule Fired: " + notification.policyName);
332 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
333 assertNotNull(notification.message);
334 assertTrue(notification.message.startsWith("Sending guard query"));
336 else if (policyName.endsWith("GUARD.RESPONSE")) {
337 logger.debug("Rule Fired: " + notification.policyName);
338 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
339 assertNotNull(notification.message);
340 assertTrue(notification.message.toLowerCase().endsWith("permit"));
342 else if (policyName.endsWith("GUARD_PERMITTED")) {
343 logger.debug("Rule Fired: " + notification.policyName);
344 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
345 assertNotNull(notification.message);
346 assertTrue(notification.message.startsWith("actor=APPC"));
348 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
349 logger.debug("Rule Fired: " + notification.policyName);
351 logger.debug("The operation timed out");
352 fail("Operation Timed Out");
354 else if (policyName.endsWith("APPC.RESPONSE")) {
355 logger.debug("Rule Fired: " + notification.policyName);
356 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
357 assertNotNull(notification.message);
358 assertTrue(notification.message.startsWith("actor=APPC"));
359 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
361 else if (policyName.endsWith("EVENT.MANAGER")) {
362 logger.debug("Rule Fired: " + notification.policyName);
363 if ("error".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
364 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
365 assertEquals("Target vnf-id could not be found", notification.message);
367 else if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
368 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
371 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
375 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
376 logger.debug("Rule Fired: " + notification.policyName);
378 logger.debug("The control loop timed out");
379 fail("Control Loop Timed Out");
382 else if (obj instanceof Request) {
383 assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
384 assertNotNull(((Request)obj).getPayload().get("generic-vnf.vnf-id"));
386 logger.debug("\n============ APPC received the request!!! ===========\n");
389 * Simulate a success response from APPC and insert
390 * the response into the working memory
392 Response appcResponse = new Response((Request)obj);
393 appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
394 appcResponse.getStatus().Value = "SUCCESS";
395 kieSession.insert(appcResponse);
400 * This method is used to simulate event messages from DCAE
401 * that start the control loop (onset message) or end the
402 * control loop (abatement message).
404 * @param policy the controlLoopName comes from the policy
405 * @param requestID the requestId for this event
406 * @param status could be onset or abated
408 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
409 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
410 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
411 event.requestID = requestID;
412 event.target = "generic-vnf.vnf-name";
413 event.closedLoopAlarmStart = Instant.now();
414 event.AAI = new HashMap<>();
415 event.AAI.put("generic-vnf.vnf-name", "testGenericVnfID");
416 event.closedLoopEventStatus = status;
417 kieSession.insert(event);
421 * This method is used to simulate event messages from DCAE
422 * that start the control loop (onset message) or end the
423 * control loop (abatement message).
425 * @param policy the controlLoopName comes from the policy
426 * @param requestID the requestId for this event
427 * @param status could be onset or abated
429 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfId) {
430 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
431 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
432 event.requestID = requestID;
433 event.target = "generic-vnf.vnf-name";
434 event.closedLoopAlarmStart = Instant.now();
435 event.AAI = new HashMap<>();
436 event.AAI.put("generic-vnf.vnf-name", vnfId);
437 event.closedLoopEventStatus = status;
438 kieSession.insert(event);
442 * This method will dump all the facts in the working memory.
444 * @param kieSession the session containing the facts
446 public void dumpFacts(KieSession kieSession) {
447 logger.debug("Fact Count: {}", kieSession.getFactCount());
448 for (FactHandle handle : kieSession.getFactHandles()) {
449 logger.debug("FACT: {}", handle);