2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.common.endpoints.event.comm.Topic.CommInfrastructure;
45 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
46 import org.onap.policy.common.endpoints.event.comm.TopicListener;
47 import org.onap.policy.common.endpoints.event.comm.TopicSink;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
49 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
50 import org.onap.policy.controlloop.ControlLoopEventStatus;
51 import org.onap.policy.controlloop.ControlLoopNotificationType;
52 import org.onap.policy.controlloop.VirtualControlLoopEvent;
53 import org.onap.policy.controlloop.VirtualControlLoopNotification;
54 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
55 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
56 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
57 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
58 import org.onap.policy.drools.system.PolicyController;
59 import org.onap.policy.drools.system.PolicyEngine;
60 import org.onap.policy.drools.utils.logging.LoggerUtil;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 public class VfwControlLoopTest implements TopicListener {
66 private static final Logger logger = LoggerFactory.getLogger(VfwControlLoopTest.class);
68 private static List<? extends TopicSink> noopTopics;
70 private static KieSession kieSession;
71 private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
72 private UUID requestId;
75 /* Set environment properties */
76 SupportUtil.setAaiProps();
77 SupportUtil.setGuardProps();
78 SupportUtil.setPuProp();
79 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
83 * Setup the simulator.
86 public static void setUpSimulator() {
87 PolicyEngine.manager.configure(new Properties());
88 assertTrue(PolicyEngine.manager.start());
89 Properties noopSinkProperties = new Properties();
90 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
91 noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
92 noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson",
93 "org.onap.policy.appc.util.Serialization,gsonPretty");
94 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
95 "org.onap.policy.controlloop.VirtualControlLoopNotification");
96 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
97 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
98 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
100 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
101 .groupId("junit.groupId")
102 .artifactId("junit.artifactId")
103 .topic("POLICY-CL-MGT")
104 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
105 .protocolFilter(new JsonProtocolFilter())
106 .customGsonCoder(null)
107 .customJacksonCoder(null)
108 .modelClassLoaderHash(1111));
109 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
110 .groupId("junit.groupId")
111 .artifactId("junit.artifactId")
113 .eventClass("org.onap.policy.appc.Request")
114 .protocolFilter(new JsonProtocolFilter())
115 .customGsonCoder(null)
116 .customJacksonCoder(null)
117 .modelClassLoaderHash(1111));
120 SupportUtil.buildAaiSim();
121 SupportUtil.buildGuardSim();
122 } catch (Exception e) {
123 fail(e.getMessage());
127 * Start the kie session
130 kieSession = startSession(
131 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/"
132 + "main/resources/__closedLoopControlName__.drl",
133 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
134 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW",
135 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
136 } catch (IOException e) {
138 logger.debug("Could not create kieSession");
139 fail("Could not create kieSession");
144 * Tear down the simulator.
147 public static void tearDownSimulator() {
149 * Gracefully shut down the kie session
151 kieSession.dispose();
153 PolicyEngine.manager.stop();
154 HttpServletServer.factory.destroy();
155 PolicyController.factory.shutdown();
156 TopicEndpoint.manager.shutdown();
160 public void successTest() {
163 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
164 * to be pulled from the queue
166 for (TopicSink sink : noopTopics) {
167 assertTrue(sink.start());
172 * Create a unique requestId
174 requestId = UUID.randomUUID();
177 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
180 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
183 kieSession.fireUntilHalt();
185 // allow object clean-up
186 kieSession.fireAllRules();
188 } catch (Exception e) {
190 logger.warn(e.toString());
196 * The only fact in memory should be Params
198 assertEquals(1, kieSession.getFactCount());
201 * Print what's left in memory
203 dumpFacts(kieSession);
207 public void aaiFailTests() {
210 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
211 * to be pulled from the queue
213 for (TopicSink sink : noopTopics) {
214 assertTrue(sink.start());
219 * Create a unique requestId
221 requestId = UUID.randomUUID();
224 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
227 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
229 kieSession.fireUntilHalt();
231 // allow object clean-up
232 kieSession.fireAllRules();
234 } catch (Exception e) {
236 logger.warn(e.toString());
237 fail(e.getMessage());
241 * The only fact in memory should be Params
243 assertEquals(1, kieSession.getFactCount());
246 * Print what's left in memory
248 dumpFacts(kieSession);
251 * Create a unique requestId
253 requestId = UUID.randomUUID();
256 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
260 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
263 kieSession.fireUntilHalt();
265 // allow object clean-up
266 kieSession.fireAllRules();
268 } catch (Exception e) {
270 logger.warn(e.toString());
271 fail(e.getMessage());
275 * The only fact in memory should be Params
277 assertEquals(1, kieSession.getFactCount());
280 * Print what's left in memory
282 dumpFacts(kieSession);
286 * This method will start a kie session and instantiate the Policy Engine.
288 * @param droolsTemplate the DRL rules file
289 * @param yamlFile the yaml file containing the policies
290 * @param policyScope scope for policy
291 * @param policyName name of the policy
292 * @param policyVersion version of the policy
293 * @return the kieSession to be used to insert facts
294 * @throws IOException IO Exception
296 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
297 String policyName, String policyVersion) throws IOException {
300 * Load policies from yaml
302 pair = SupportUtil.loadYaml(yamlFile);
304 assertNotNull(pair.first);
305 assertNotNull(pair.first.getControlLoop());
306 assertNotNull(pair.first.getControlLoop().getControlLoopName());
307 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
310 * Construct a kie session
312 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
313 pair.first.getControlLoop().getControlLoopName(),
314 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
317 * Retrieve the Policy Engine
320 logger.debug("============");
321 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
322 logger.debug("============");
328 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
331 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
333 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
337 if ("POLICY-CL-MGT".equals(topic)) {
338 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
339 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
340 } else if ("APPC-CL".equals(topic)) {
341 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event,
342 org.onap.policy.appc.Request.class);
345 if (obj instanceof VirtualControlLoopNotification) {
346 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
347 String policyName = notification.getPolicyName();
348 if (policyName.endsWith("EVENT")) {
349 logger.debug("Rule Fired: " + notification.getPolicyName());
350 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
351 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
352 logger.debug("Rule Fired: " + notification.getPolicyName());
353 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
354 assertNotNull(notification.getMessage());
355 assertTrue(notification.getMessage().startsWith("Sending guard query"));
356 } else if (policyName.endsWith("GUARD.RESPONSE")) {
357 logger.debug("Rule Fired: " + notification.getPolicyName());
358 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
359 assertNotNull(notification.getMessage());
360 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
361 } else if (policyName.endsWith("GUARD_PERMITTED")) {
362 logger.debug("Rule Fired: " + notification.getPolicyName());
363 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
364 assertNotNull(notification.getMessage());
365 assertTrue(notification.getMessage().startsWith("actor=APPC"));
366 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
367 logger.debug("Rule Fired: " + notification.getPolicyName());
369 logger.debug("The operation timed out");
370 fail("Operation Timed Out");
371 } else if (policyName.endsWith("APPC.RESPONSE")) {
372 logger.debug("Rule Fired: " + notification.getPolicyName());
373 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
374 assertNotNull(notification.getMessage());
375 assertTrue(notification.getMessage().startsWith("actor=APPC"));
376 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
377 } else if (policyName.endsWith("EVENT.MANAGER")) {
378 logger.debug("Rule Fired: " + notification.getPolicyName());
379 if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
380 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
381 assertEquals("Target vnf-id could not be found", notification.getMessage());
382 } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
383 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
385 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
388 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
389 logger.debug("Rule Fired: " + notification.getPolicyName());
391 logger.debug("The control loop timed out");
392 fail("Control Loop Timed Out");
394 } else if (obj instanceof Request) {
395 assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1"));
396 assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id"));
398 logger.debug("\n============ APPC received the request!!! ===========\n");
401 * Simulate a success response from APPC and insert the response into the working memory
403 Response appcResponse = new Response((Request) obj);
404 appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue());
405 appcResponse.getStatus().setValue("SUCCESS");
406 kieSession.insert(appcResponse);
411 * This method is used to simulate event messages from DCAE that start the control loop (onset
412 * message) or end the control loop (abatement message).
414 * @param policy the controlLoopName comes from the policy
415 * @param requestId the requestId for this event
416 * @param status could be onset or abated
418 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
419 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
420 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
421 event.setRequestId(requestId);
422 event.setTarget("generic-vnf.vnf-name");
423 event.setClosedLoopAlarmStart(Instant.now());
424 event.setAai(new HashMap<>());
425 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID");
426 event.setClosedLoopEventStatus(status);
427 kieSession.insert(event);
431 * This method is used to simulate event messages from DCAE that start the control loop (onset
432 * message) or end the control loop (abatement message).
434 * @param policy the controlLoopName comes from the policy
435 * @param requestId the requestId for this event
436 * @param status could be onset or abated
438 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfId) {
439 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
440 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
441 event.setRequestId(requestId);
442 event.setTarget("generic-vnf.vnf-name");
443 event.setClosedLoopAlarmStart(Instant.now());
444 event.setAai(new HashMap<>());
445 event.getAai().put("generic-vnf.vnf-name", vnfId);
446 event.setClosedLoopEventStatus(status);
447 kieSession.insert(event);
451 * This method will dump all the facts in the working memory.
453 * @param kieSession the session containing the facts
455 public void dumpFacts(KieSession kieSession) {
456 logger.debug("Fact Count: {}", kieSession.getFactCount());
457 for (FactHandle handle : kieSession.getFactHandles()) {
458 logger.debug("FACT: {}", handle);