2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 Intel Corp. All rights reserved.
6 * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.template.demo;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
29 import java.io.IOException;
30 import java.net.URLEncoder;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Properties;
35 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.common.endpoints.event.comm.Topic.CommInfrastructure;
42 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
43 import org.onap.policy.common.endpoints.event.comm.TopicListener;
44 import org.onap.policy.common.endpoints.event.comm.TopicSink;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
46 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
47 import org.onap.policy.controlloop.ControlLoopEventStatus;
48 import org.onap.policy.controlloop.ControlLoopNotificationType;
49 import org.onap.policy.controlloop.ControlLoopTargetType;
50 import org.onap.policy.controlloop.VirtualControlLoopEvent;
51 import org.onap.policy.controlloop.VirtualControlLoopNotification;
52 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
55 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
56 import org.onap.policy.drools.system.PolicyController;
57 import org.onap.policy.drools.system.PolicyEngine;
58 import org.onap.policy.drools.utils.logging.LoggerUtil;
59 import org.onap.policy.vfc.VfcRequest;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 public class VfcControlLoopTest implements TopicListener {
66 private static final Logger logger = LoggerFactory.getLogger(VfcControlLoopTest.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.setVfcProps();
78 SupportUtil.setGuardProps();
79 SupportUtil.setPuProp();
80 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
84 * Setup the simulator.
87 public static void setUpSimulator() {
88 PolicyEngine.manager.configure(new Properties());
89 assertTrue(PolicyEngine.manager.start());
90 Properties noopSinkProperties = new Properties();
91 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
92 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
93 "org.onap.policy.controlloop.VirtualControlLoopNotification");
94 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
95 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
96 noopTopics = TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties);
98 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
99 .groupId("junit.groupId")
100 .artifactId("junit.artifactId")
101 .topic("POLICY-CL-MGT")
102 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
103 .protocolFilter(new JsonProtocolFilter())
104 .modelClassLoaderHash(1111));
107 SupportUtil.buildAaiSim();
108 SupportUtil.buildVfcSim();
109 SupportUtil.buildGuardSim();
110 } catch (Exception e) {
111 fail(e.getMessage());
115 * Start the kie session
118 kieSession = startSession(
119 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
120 + "src/main/resources/__closedLoopControlName__.drl",
121 "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0");
122 } catch (IOException e) {
124 logger.debug("Could not create kieSession");
125 fail("Could not create kieSession");
130 * Tear down the simulator.
133 public static void tearDownSimulator() {
136 * Gracefully shut down the kie session
138 kieSession.dispose();
140 PolicyEngine.manager.stop();
141 HttpServletServerFactoryInstance.getServerFactory().destroy();
142 PolicyController.factory.shutdown();
143 TopicEndpointManager.getManager().shutdown();
147 public void successTest() throws IOException {
150 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
151 * to be pulled from the queue
153 for (TopicSink sink : noopTopics) {
154 assertTrue(sink.start());
159 * Create a unique requestId
161 requestId = UUID.randomUUID();
164 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
167 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
169 kieSession.fireUntilHalt();
171 // allow object clean-up
172 kieSession.fireAllRules();
175 * The only fact in memory should be Params
177 assertEquals(1, kieSession.getFactCount());
180 * Print what's left in memory
182 dumpFacts(kieSession);
186 public void nullRequestTest() throws IOException {
189 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
190 * to be pulled from the queue
192 for (TopicSink sink : noopTopics) {
193 assertTrue(sink.start());
198 * Create a unique requestId
200 requestId = UUID.randomUUID();
203 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
207 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
208 event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
209 event.setRequestId(UUID.randomUUID());
210 event.setClosedLoopEventClient("tca.instance00009");
211 event.setTargetType(ControlLoopTargetType.VM);
212 event.setTarget("vserver.vserver-name");
213 event.setFrom("DCAE");
214 event.setClosedLoopAlarmStart(Instant.now());
215 event.setAai(new HashMap<String, String>());
216 event.getAai().put("vserver.vserver-name", "nullRequest");
217 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
218 kieSession.insert(event);
220 kieSession.fireUntilHalt();
222 // allow object clean-up
223 kieSession.fireAllRules();
226 * The only fact in memory should be Params
228 assertEquals(1, kieSession.getFactCount());
231 * Print what's left in memory
233 dumpFacts(kieSession);
237 * This method will start a kie session and instantiate the Policy Engine.
239 * @param droolsTemplate the DRL rules file
240 * @param yamlFile the yaml file containing the policies
241 * @param policyScope scope for policy
242 * @param policyName name of the policy
243 * @param policyVersion version of the policy
244 * @return the kieSession to be used to insert facts
245 * @throws IOException IO Exception
247 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
248 String policyName, String policyVersion) throws IOException {
251 * Load policies from yaml
253 pair = SupportUtil.loadYaml(yamlFile);
255 assertNotNull(pair.first);
256 assertNotNull(pair.first.getControlLoop());
257 assertNotNull(pair.first.getControlLoop().getControlLoopName());
258 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
261 * Construct a kie session
263 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
264 pair.first.getControlLoop().getControlLoopName(),
265 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
268 * Retrieve the Policy Engine
271 logger.debug("============");
272 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
273 logger.debug("============");
281 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
284 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
286 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
290 if ("POLICY-CL-MGT".equals(topic)) {
291 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
292 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
295 if (obj instanceof VirtualControlLoopNotification) {
296 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
297 String policyName = notification.getPolicyName();
298 if (policyName.endsWith("EVENT")) {
299 logger.debug("Rule Fired: " + notification.getPolicyName());
300 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
301 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
302 logger.debug("Rule Fired: " + notification.getPolicyName());
303 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
304 assertNotNull(notification.getMessage());
305 assertTrue(notification.getMessage().startsWith("Sending guard query"));
306 } else if (policyName.endsWith("GUARD.RESPONSE")) {
307 logger.debug("Rule Fired: " + notification.getPolicyName());
308 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
309 assertNotNull(notification.getMessage());
310 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
311 } else if (policyName.endsWith("GUARD_PERMITTED")) {
312 logger.debug("Rule Fired: " + notification.getPolicyName());
313 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
314 assertNotNull(notification.getMessage());
315 assertTrue(notification.getMessage().startsWith("actor=VFC"));
316 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
317 logger.debug("Rule Fired: " + notification.getPolicyName());
319 logger.debug("The operation timed out");
320 fail("Operation Timed Out");
321 } else if (policyName.endsWith("VFC.RESPONSE")) {
322 logger.debug("Rule Fired: " + notification.getPolicyName());
323 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
324 assertNotNull(notification.getMessage());
325 assertTrue(notification.getMessage().startsWith("actor=VFC"));
326 } else if (policyName.endsWith("EVENT.MANAGER")) {
327 logger.debug("Rule Fired: " + notification.getPolicyName());
328 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
329 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
331 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
334 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
335 logger.debug("Rule Fired: " + notification.getPolicyName());
337 logger.debug("The control loop timed out");
338 fail("Control Loop Timed Out");
340 } else if (obj instanceof VfcRequest) {
341 logger.debug("\n============ VFC received the request!!! ===========\n");
346 * This method is used to simulate event messages from DCAE that start the control loop (onset
347 * message) or end the control loop (abatement message).
349 * @param policy the controlLoopName comes from the policy
350 * @param requestId the requestId for this event
351 * @param status could be onset or abated
353 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
354 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
355 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
356 event.setRequestId(UUID.randomUUID());
357 event.setClosedLoopEventClient("tca.instance00009");
358 event.setTargetType(ControlLoopTargetType.VM);
359 event.setTarget("vserver.vserver-name");
360 event.setFrom("DCAE");
361 event.setClosedLoopAlarmStart(Instant.now());
362 event.setAai(new HashMap<String, String>());
363 event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
364 event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
365 event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
366 event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
367 event.getAai().put("vserver.is-closed-loop-disabled", "false");
368 event.getAai().put("vserver.prov-status", "ACTIVE");
369 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
370 kieSession.insert(event);
374 * Dumps the kie session facts.
376 * @param kieSession input session
378 public static void dumpFacts(KieSession kieSession) {
379 logger.debug("Fact Count: " + kieSession.getFactCount());
380 for (FactHandle handle : kieSession.getFactHandles()) {
381 logger.debug("FACT: " + handle);