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.Ignore;
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.appc.Request;
43 import org.onap.policy.appc.Response;
44 import org.onap.policy.appc.ResponseCode;
45 import org.onap.policy.controlloop.ControlLoopEventStatus;
46 import org.onap.policy.controlloop.ControlLoopNotificationType;
47 import org.onap.policy.controlloop.VirtualControlLoopEvent;
48 import org.onap.policy.controlloop.VirtualControlLoopNotification;
49 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
50 import org.onap.policy.drools.event.comm.TopicEndpoint;
51 import org.onap.policy.drools.event.comm.TopicListener;
52 import org.onap.policy.drools.event.comm.TopicSink;
53 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
54 import org.onap.policy.drools.http.server.HttpServletServer;
55 import org.onap.policy.drools.properties.PolicyProperties;
56 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
57 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
58 import org.onap.policy.drools.system.PolicyEngine;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 public class VFWControlLoopTest implements TopicListener {
64 private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
66 private static List<? extends TopicSink> noopTopics;
68 private KieSession kieSession;
69 private Util.Pair<ControlLoopPolicy, String> pair;
70 private UUID requestID;
73 /* Set environment properties */
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-CL,POLICY-CL-MGT");
85 noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
86 noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", "org.onap.policy.appc.util.Serialization,gsonPretty");
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-CL", "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111);
97 } catch (Exception e) {
103 public static void tearDownSimulator() {
104 HttpServletServer.factory.destroy();
105 PolicyEngine.manager.shutdown();
109 public void successTest() {
112 * Start the kie session
115 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
116 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
117 "service=ServiceDemo;resource=Res1Demo;type=operational",
119 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
120 } catch (IOException e) {
122 logger.debug("Could not create kieSession");
123 fail("Could not create kieSession");
127 * Allows the PolicyEngine to callback to this object to
128 * notify that there is an event ready to be pulled
131 for (TopicSink sink : noopTopics) {
132 assertTrue(sink.start());
137 * Create a unique requestId
139 requestID = UUID.randomUUID();
142 * Simulate an onset event the policy engine will
143 * receive from DCAE to kick off processing through
146 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
149 kieSession.fireUntilHalt();
151 catch (Exception e) {
153 logger.warn(e.toString());
159 * The only fact in memory should be Params
161 assertEquals(1, kieSession.getFactCount());
164 * Print what's left in memory
166 dumpFacts(kieSession);
169 * Gracefully shut down the kie session
171 kieSession.dispose();
175 public void namedQueryFailTest() {
178 * Start the kie session
181 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
182 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
183 "service=ServiceDemo;resource=Res1Demo;type=operational",
185 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
186 } catch (IOException e) {
188 logger.debug("Could not create kieSession");
189 fail("Could not create kieSession");
193 * Allows the PolicyEngine to callback to this object to
194 * notify that there is an event ready to be pulled
197 for (TopicSink sink : noopTopics) {
198 assertTrue(sink.start());
203 * Create a unique requestId
205 requestID = UUID.randomUUID();
208 * Simulate an onset event the policy engine will
209 * receive from DCAE to kick off processing through
212 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error");
215 kieSession.fireUntilHalt();
217 catch (Exception e) {
219 logger.warn(e.toString());
220 fail(e.getMessage());
225 * The only fact in memory should be Params
227 assertEquals(1, kieSession.getFactCount());
230 * Print what's left in memory
232 dumpFacts(kieSession);
235 * Gracefully shut down the kie session
237 kieSession.dispose();
241 * This method will start a kie session and instantiate
244 * @param droolsTemplate
247 * the yaml file containing the policies
252 * @param policyVersion
253 * version of the policy
254 * @return the kieSession to be used to insert facts
255 * @throws IOException
257 private KieSession startSession(String droolsTemplate,
261 String policyVersion) throws IOException {
264 * Load policies from yaml
266 pair = Util.loadYaml(yamlFile);
268 assertNotNull(pair.a);
269 assertNotNull(pair.a.getControlLoop());
270 assertNotNull(pair.a.getControlLoop().getControlLoopName());
271 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
274 * Construct a kie session
276 final KieSession kieSession = Util.buildContainer(droolsTemplate,
277 pair.a.getControlLoop().getControlLoopName(),
281 URLEncoder.encode(pair.b, "UTF-8"));
284 * Retrieve the Policy Engine
287 logger.debug("============");
288 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
289 logger.debug("============");
295 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
297 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
299 * Pull the object that was sent out to DMAAP and make
300 * sure it is a ControlLoopNoticiation of type active
303 if ("POLICY-CL-MGT".equals(topic)) {
304 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
306 else if ("APPC-CL".equals(topic))
307 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, org.onap.policy.appc.Request.class);
309 if (obj instanceof VirtualControlLoopNotification) {
310 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
311 String policyName = notification.policyName;
312 if (policyName.endsWith("EVENT")) {
313 logger.debug("Rule Fired: " + notification.policyName);
314 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
316 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
317 logger.debug("Rule Fired: " + notification.policyName);
318 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
319 assertNotNull(notification.message);
320 assertTrue(notification.message.startsWith("Sending guard query"));
322 else if (policyName.endsWith("GUARD.RESPONSE")) {
323 logger.debug("Rule Fired: " + notification.policyName);
324 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
325 assertNotNull(notification.message);
326 assertTrue(notification.message.toLowerCase().endsWith("permit"));
328 else if (policyName.endsWith("GUARD_PERMITTED")) {
329 logger.debug("Rule Fired: " + notification.policyName);
330 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
331 assertNotNull(notification.message);
332 assertTrue(notification.message.startsWith("actor=APPC"));
334 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
335 logger.debug("Rule Fired: " + notification.policyName);
337 logger.debug("The operation timed out");
338 fail("Operation Timed Out");
340 else if (policyName.endsWith("APPC.RESPONSE")) {
341 logger.debug("Rule Fired: " + notification.policyName);
342 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
343 assertNotNull(notification.message);
344 assertTrue(notification.message.startsWith("actor=APPC"));
345 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
347 else if (policyName.endsWith("EVENT.MANAGER")) {
348 logger.debug("Rule Fired: " + notification.policyName);
349 if ("error".equals(notification.AAI.get("generic-vnf.vnf-id"))) {
350 assertTrue(ControlLoopNotificationType.FINAL_FAILURE.equals(notification.notification));
351 assertEquals("Exception in processing closed loop", notification.message);
354 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
358 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
359 logger.debug("Rule Fired: " + notification.policyName);
361 logger.debug("The control loop timed out");
362 fail("Control Loop Timed Out");
365 else if (obj instanceof Request) {
366 assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
368 logger.debug("\n============ APPC received the request!!! ===========\n");
371 * Simulate a success response from APPC and insert
372 * the response into the working memory
374 Response appcResponse = new Response((Request)obj);
375 appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
376 appcResponse.getStatus().Value = "SUCCESS";
377 kieSession.insert(appcResponse);
382 * This method is used to simulate event messages from DCAE
383 * that start the control loop (onset message) or end the
384 * control loop (abatement message).
386 * @param policy the controlLoopName comes from the policy
387 * @param requestID the requestId for this event
388 * @param status could be onset or abated
390 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
391 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
392 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
393 event.requestID = requestID;
394 event.target = "generic-vnf.vnf-id";
395 event.closedLoopAlarmStart = Instant.now();
396 event.AAI = new HashMap<>();
397 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
398 event.closedLoopEventStatus = status;
399 kieSession.insert(event);
403 * This method is used to simulate event messages from DCAE
404 * that start the control loop (onset message) or end the
405 * control loop (abatement message).
407 * @param policy the controlLoopName comes from the policy
408 * @param requestID the requestId for this event
409 * @param status could be onset or abated
411 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfId) {
412 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
413 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
414 event.requestID = requestID;
415 event.target = "generic-vnf.vnf-id";
416 event.closedLoopAlarmStart = Instant.now();
417 event.AAI = new HashMap<>();
418 event.AAI.put("generic-vnf.vnf-id", vnfId);
419 event.closedLoopEventStatus = status;
420 kieSession.insert(event);
424 * This method will dump all the facts in the working memory.
426 * @param kieSession the session containing the facts
428 public void dumpFacts(KieSession kieSession) {
429 logger.debug("Fact Count: {}", kieSession.getFactCount());
430 for (FactHandle handle : kieSession.getFactHandles()) {
431 logger.debug("FACT: {}", handle);