2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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;
35 import org.junit.AfterClass;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.kie.api.runtime.KieSession;
39 import org.kie.api.runtime.rule.FactHandle;
40 import org.onap.policy.appc.Request;
41 import org.onap.policy.appc.Response;
42 import org.onap.policy.appc.ResponseCode;
43 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
44 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
45 import org.onap.policy.common.endpoints.event.comm.TopicListener;
46 import org.onap.policy.common.endpoints.event.comm.TopicSink;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
48 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
49 import org.onap.policy.controlloop.ControlLoopEventStatus;
50 import org.onap.policy.controlloop.ControlLoopNotificationType;
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.EventProtocolParams;
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.logging.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 SupportUtil.Pair<ControlLoopPolicy, String> pair;
71 private UUID requestId;
74 /* Set environment properties */
75 SupportUtil.setAaiProps();
76 SupportUtil.setGuardProps();
77 SupportUtil.setPuProp();
78 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
82 * Setup the simulator.
85 public static void setUpSimulator() {
86 PolicyEngine.manager.configure(new Properties());
87 assertTrue(PolicyEngine.manager.start());
88 Properties noopSinkProperties = new Properties();
89 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
90 noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
91 noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson",
92 "org.onap.policy.appc.util.Serialization,gsonPretty");
93 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
94 "org.onap.policy.controlloop.VirtualControlLoopNotification");
95 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
96 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
97 noopTopics = TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties);
99 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
100 .groupId("junit.groupId")
101 .artifactId("junit.artifactId")
102 .topic("POLICY-CL-MGT")
103 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
104 .protocolFilter(new JsonProtocolFilter())
105 .modelClassLoaderHash(1111));
106 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
107 .groupId("junit.groupId")
108 .artifactId("junit.artifactId")
110 .eventClass("org.onap.policy.appc.Request")
111 .protocolFilter(new JsonProtocolFilter())
112 .modelClassLoaderHash(1111));
115 SupportUtil.buildAaiSim();
116 SupportUtil.buildGuardSim();
117 } catch (Exception e) {
118 fail(e.getMessage());
122 * Start the kie session
125 kieSession = startSession(
126 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/"
127 + "main/resources/__closedLoopControlName__.drl",
128 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
129 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW",
130 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
131 } catch (IOException e) {
133 logger.debug("Could not create kieSession");
134 fail("Could not create kieSession");
139 * Tear down the simulator.
142 public static void tearDownSimulator() {
144 * Gracefully shut down the kie session
146 kieSession.dispose();
148 PolicyEngine.manager.stop();
149 HttpServletServerFactoryInstance.getServerFactory().destroy();
150 PolicyController.factory.shutdown();
151 TopicEndpointManager.getManager().shutdown();
155 public void successTest() {
158 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
159 * to be pulled from the queue
161 for (TopicSink sink : noopTopics) {
162 assertTrue(sink.start());
167 * Create a unique requestId
169 requestId = UUID.randomUUID();
172 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
175 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
178 kieSession.fireUntilHalt();
180 // allow object clean-up
181 kieSession.fireAllRules();
183 } catch (Exception e) {
185 logger.warn(e.toString());
191 * The only fact in memory should be Params
193 assertEquals(1, kieSession.getFactCount());
196 * Print what's left in memory
198 dumpFacts(kieSession);
202 public void aaiFailTests() {
205 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
206 * to be pulled from the queue
208 for (TopicSink sink : noopTopics) {
209 assertTrue(sink.start());
214 * Create a unique requestId
216 requestId = UUID.randomUUID();
219 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
222 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
224 kieSession.fireUntilHalt();
226 // allow object clean-up
227 kieSession.fireAllRules();
229 } catch (Exception e) {
231 logger.warn(e.toString());
232 fail(e.getMessage());
236 * The only fact in memory should be Params
238 assertEquals(1, kieSession.getFactCount());
241 * Print what's left in memory
243 dumpFacts(kieSession);
246 * Create a unique requestId
248 requestId = UUID.randomUUID();
251 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
255 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
258 kieSession.fireUntilHalt();
260 // allow object clean-up
261 kieSession.fireAllRules();
263 } catch (Exception e) {
265 logger.warn(e.toString());
266 fail(e.getMessage());
270 * The only fact in memory should be Params
272 assertEquals(1, kieSession.getFactCount());
275 * Print what's left in memory
277 dumpFacts(kieSession);
281 * This method will start a kie session and instantiate the Policy Engine.
283 * @param droolsTemplate the DRL rules file
284 * @param yamlFile the yaml file containing the policies
285 * @param policyScope scope for policy
286 * @param policyName name of the policy
287 * @param policyVersion version of the policy
288 * @return the kieSession to be used to insert facts
289 * @throws IOException IO Exception
291 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
292 String policyName, String policyVersion) throws IOException {
295 * Load policies from yaml
297 pair = SupportUtil.loadYaml(yamlFile);
299 assertNotNull(pair.first);
300 assertNotNull(pair.first.getControlLoop());
301 assertNotNull(pair.first.getControlLoop().getControlLoopName());
302 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
305 * Construct a kie session
307 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
308 pair.first.getControlLoop().getControlLoopName(),
309 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
312 * Retrieve the Policy Engine
315 logger.debug("============");
316 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
317 logger.debug("============");
323 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
326 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
328 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
332 if ("POLICY-CL-MGT".equals(topic)) {
333 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
334 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
335 } else if ("APPC-CL".equals(topic)) {
336 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event,
337 org.onap.policy.appc.Request.class);
340 if (obj instanceof VirtualControlLoopNotification) {
341 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
342 String policyName = notification.getPolicyName();
343 if (policyName.endsWith("EVENT")) {
344 logger.debug("Rule Fired: " + notification.getPolicyName());
345 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
346 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
347 logger.debug("Rule Fired: " + notification.getPolicyName());
348 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
349 assertNotNull(notification.getMessage());
350 assertTrue(notification.getMessage().startsWith("Sending guard query"));
351 } else if (policyName.endsWith("GUARD.RESPONSE")) {
352 logger.debug("Rule Fired: " + notification.getPolicyName());
353 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
354 assertNotNull(notification.getMessage());
355 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
356 } else if (policyName.endsWith("GUARD_PERMITTED")) {
357 logger.debug("Rule Fired: " + notification.getPolicyName());
358 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
359 assertNotNull(notification.getMessage());
360 assertTrue(notification.getMessage().startsWith("actor=APPC"));
361 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
362 logger.debug("Rule Fired: " + notification.getPolicyName());
364 logger.debug("The operation timed out");
365 fail("Operation Timed Out");
366 } else if (policyName.endsWith("APPC.RESPONSE")) {
367 logger.debug("Rule Fired: " + notification.getPolicyName());
368 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
369 assertNotNull(notification.getMessage());
370 assertTrue(notification.getMessage().startsWith("actor=APPC"));
371 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
372 } else if (policyName.endsWith("EVENT.MANAGER")) {
373 logger.debug("Rule Fired: " + notification.getPolicyName());
374 if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
375 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
376 assertEquals("Target vnf-id could not be found", notification.getMessage());
377 } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
378 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
380 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
383 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
384 logger.debug("Rule Fired: " + notification.getPolicyName());
386 logger.debug("The control loop timed out");
387 fail("Control Loop Timed Out");
389 } else if (obj instanceof Request) {
390 assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1"));
391 assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id"));
393 logger.debug("\n============ APPC received the request!!! ===========\n");
396 * Simulate a success response from APPC and insert the response into the working memory
398 Response appcResponse = new Response((Request) obj);
399 appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue());
400 appcResponse.getStatus().setValue("SUCCESS");
401 kieSession.insert(appcResponse);
406 * This method is used to simulate event messages from DCAE that start the control loop (onset
407 * message) or end the control loop (abatement message).
409 * @param policy the controlLoopName comes from the policy
410 * @param requestId the requestId for this event
411 * @param status could be onset or abated
413 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
414 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
415 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
416 event.setRequestId(requestId);
417 event.setTarget("generic-vnf.vnf-name");
418 event.setClosedLoopAlarmStart(Instant.now());
419 event.setAai(new HashMap<>());
420 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID");
421 event.setClosedLoopEventStatus(status);
422 kieSession.insert(event);
426 * This method is used to simulate event messages from DCAE that start the control loop (onset
427 * message) or end the control loop (abatement message).
429 * @param policy the controlLoopName comes from the policy
430 * @param requestId the requestId for this event
431 * @param status could be onset or abated
433 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfId) {
434 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
435 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
436 event.setRequestId(requestId);
437 event.setTarget("generic-vnf.vnf-name");
438 event.setClosedLoopAlarmStart(Instant.now());
439 event.setAai(new HashMap<>());
440 event.getAai().put("generic-vnf.vnf-name", vnfId);
441 event.setClosedLoopEventStatus(status);
442 kieSession.insert(event);
446 * This method will dump all the facts in the working memory.
448 * @param kieSession the session containing the facts
450 public void dumpFacts(KieSession kieSession) {
451 logger.debug("Fact Count: {}", kieSession.getFactCount());
452 for (FactHandle handle : kieSession.getFactHandles()) {
453 logger.debug("FACT: {}", handle);