2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 Intel Corp. All rights reserved.
6 * Modifications Copyright (C) 2018 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;
37 import org.junit.AfterClass;
38 import org.junit.BeforeClass;
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.common.endpoints.event.comm.Topic.CommInfrastructure;
43 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
44 import org.onap.policy.common.endpoints.event.comm.TopicListener;
45 import org.onap.policy.common.endpoints.event.comm.TopicSink;
46 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
47 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
48 import org.onap.policy.controlloop.ControlLoopEventStatus;
49 import org.onap.policy.controlloop.ControlLoopNotificationType;
50 import org.onap.policy.controlloop.ControlLoopTargetType;
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.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 Util.Pair<ControlLoopPolicy, String> pair;
72 private UUID requestId;
75 /* Set environment properties */
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 = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
98 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
99 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
105 Util.buildGuardSim();
106 } catch (Exception e) {
107 fail(e.getMessage());
111 * Start the kie session
114 kieSession = startSession(
115 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
116 + "src/main/resources/__closedLoopControlName__.drl",
117 "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0");
118 } catch (IOException e) {
120 logger.debug("Could not create kieSession");
121 fail("Could not create kieSession");
126 * Tear down the simulator.
129 public static void tearDownSimulator() {
132 * Gracefully shut down the kie session
134 kieSession.dispose();
136 PolicyEngine.manager.stop();
137 HttpServletServer.factory.destroy();
138 PolicyController.factory.shutdown();
139 TopicEndpoint.manager.shutdown();
143 public void successTest() throws IOException {
146 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
147 * to be pulled from the queue
149 for (TopicSink sink : noopTopics) {
150 assertTrue(sink.start());
155 * Create a unique requestId
157 requestId = UUID.randomUUID();
160 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
163 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
165 kieSession.fireUntilHalt();
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 nullRequestTest() throws IOException {
182 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
183 * to be pulled from the queue
185 for (TopicSink sink : noopTopics) {
186 assertTrue(sink.start());
191 * Create a unique requestId
193 requestId = UUID.randomUUID();
196 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
200 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
201 event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
202 event.setRequestId(UUID.randomUUID());
203 event.setClosedLoopEventClient("tca.instance00009");
204 event.setTargetType(ControlLoopTargetType.VM);
205 event.setTarget("vserver.vserver-name");
206 event.setFrom("DCAE");
207 event.setClosedLoopAlarmStart(Instant.now());
208 event.setAai(new HashMap<String, String>());
209 event.getAai().put("vserver.vserver-name", "nullRequest");
210 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
211 kieSession.insert(event);
213 kieSession.fireUntilHalt();
216 * The only fact in memory should be Params
218 assertEquals(1, kieSession.getFactCount());
221 * Print what's left in memory
223 dumpFacts(kieSession);
227 * This method will start a kie session and instantiate the Policy Engine.
229 * @param droolsTemplate the DRL rules file
230 * @param yamlFile the yaml file containing the policies
231 * @param policyScope scope for policy
232 * @param policyName name of the policy
233 * @param policyVersion version of the policy
234 * @return the kieSession to be used to insert facts
235 * @throws IOException IO Exception
237 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
238 String policyName, String policyVersion) throws IOException {
241 * Load policies from yaml
243 pair = Util.loadYaml(yamlFile);
245 assertNotNull(pair.first);
246 assertNotNull(pair.first.getControlLoop());
247 assertNotNull(pair.first.getControlLoop().getControlLoopName());
248 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
251 * Construct a kie session
253 final KieSession kieSession = Util.buildContainer(droolsTemplate,
254 pair.first.getControlLoop().getControlLoopName(),
255 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
258 * Retrieve the Policy Engine
261 logger.debug("============");
262 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
263 logger.debug("============");
271 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
274 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
276 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
280 if ("POLICY-CL-MGT".equals(topic)) {
281 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
282 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
285 if (obj instanceof VirtualControlLoopNotification) {
286 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
287 String policyName = notification.getPolicyName();
288 if (policyName.endsWith("EVENT")) {
289 logger.debug("Rule Fired: " + notification.getPolicyName());
290 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
291 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
292 logger.debug("Rule Fired: " + notification.getPolicyName());
293 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
294 assertNotNull(notification.getMessage());
295 assertTrue(notification.getMessage().startsWith("Sending guard query"));
296 } else if (policyName.endsWith("GUARD.RESPONSE")) {
297 logger.debug("Rule Fired: " + notification.getPolicyName());
298 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
299 assertNotNull(notification.getMessage());
300 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
301 } else if (policyName.endsWith("GUARD_PERMITTED")) {
302 logger.debug("Rule Fired: " + notification.getPolicyName());
303 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
304 assertNotNull(notification.getMessage());
305 assertTrue(notification.getMessage().startsWith("actor=VFC"));
306 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
307 logger.debug("Rule Fired: " + notification.getPolicyName());
309 logger.debug("The operation timed out");
310 fail("Operation Timed Out");
311 } else if (policyName.endsWith("VFC.RESPONSE")) {
312 logger.debug("Rule Fired: " + notification.getPolicyName());
313 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
314 assertNotNull(notification.getMessage());
315 assertTrue(notification.getMessage().startsWith("actor=VFC"));
316 } else if (policyName.endsWith("EVENT.MANAGER")) {
317 logger.debug("Rule Fired: " + notification.getPolicyName());
318 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
319 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
321 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
324 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
325 logger.debug("Rule Fired: " + notification.getPolicyName());
327 logger.debug("The control loop timed out");
328 fail("Control Loop Timed Out");
330 } else if (obj instanceof VFCRequest) {
331 logger.debug("\n============ VFC received the request!!! ===========\n");
336 * This method is used to simulate event messages from DCAE that start the control loop (onset
337 * message) or end the control loop (abatement message).
339 * @param policy the controlLoopName comes from the policy
340 * @param requestID the requestId for this event
341 * @param status could be onset or abated
343 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
344 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
345 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
346 event.setRequestId(UUID.randomUUID());
347 event.setClosedLoopEventClient("tca.instance00009");
348 event.setTargetType(ControlLoopTargetType.VM);
349 event.setTarget("vserver.vserver-name");
350 event.setFrom("DCAE");
351 event.setClosedLoopAlarmStart(Instant.now());
352 event.setAai(new HashMap<String, String>());
353 event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
354 event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
355 event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
356 event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
357 event.getAai().put("vserver.is-closed-loop-disabled", "false");
358 event.getAai().put("vserver.prov-status", "ACTIVE");
359 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
360 kieSession.insert(event);
364 * Dumps the kie session facts.
366 * @param kieSession input session
368 public static void dumpFacts(KieSession kieSession) {
369 logger.debug("Fact Count: " + kieSession.getFactCount());
370 for (FactHandle handle : kieSession.getFactHandles()) {
371 logger.debug("FACT: " + handle);