2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2018 Huawei. All rights reserved.
4 * Modifications Copyright (C) 2019 AT&T Intellectual Property.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ============LICENSE_END=========================================================
20 package org.onap.policy.template.demo;
22 import static org.junit.Assert.assertEquals;
23 import static org.junit.Assert.assertNotNull;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
27 import java.io.IOException;
28 import java.net.URLEncoder;
29 import java.time.Instant;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Properties;
33 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.common.endpoints.event.comm.Topic.CommInfrastructure;
41 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
42 import org.onap.policy.common.endpoints.event.comm.TopicListener;
43 import org.onap.policy.common.endpoints.event.comm.TopicSink;
44 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
45 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
46 import org.onap.policy.controlloop.ControlLoopEventStatus;
47 import org.onap.policy.controlloop.ControlLoopNotificationType;
48 import org.onap.policy.controlloop.ControlLoopTargetType;
49 import org.onap.policy.controlloop.VirtualControlLoopEvent;
50 import org.onap.policy.controlloop.VirtualControlLoopNotification;
51 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
52 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
53 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyController;
56 import org.onap.policy.drools.system.PolicyEngine;
57 import org.onap.policy.drools.utils.logging.LoggerUtil;
58 import org.onap.policy.sdnc.SdncRequest;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 public class CcvpnControlLoopTest implements TopicListener {
64 private static final Logger logger = LoggerFactory.getLogger(CcvpnControlLoopTest.class);
66 private static List<? extends TopicSink> noopTopics;
68 private static KieSession kieSession;
69 private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
72 /* Set environment properties */
73 SupportUtil.setAaiProps();
74 SupportUtil.setSdncProps();
75 SupportUtil.setGuardProps();
76 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
80 * Setup the simulator.
83 public static void setUpSimulator() {
84 PolicyEngine.manager.configure(new Properties());
85 assertTrue(PolicyEngine.manager.start());
86 Properties noopSinkProperties = new Properties();
87 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
88 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
89 "org.onap.policy.controlloop.VirtualControlLoopNotification");
90 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
91 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
92 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
94 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
95 .groupId("junit.groupId")
96 .artifactId("junit.artifactId")
97 .topic("POLICY-CL-MGT")
98 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
99 .protocolFilter(new JsonProtocolFilter())
100 .modelClassLoaderHash(1111));
103 SupportUtil.buildAaiSim();
104 SupportUtil.buildSdncSim();
105 SupportUtil.buildGuardSim();
106 } catch (Exception e) {
107 fail(e.getMessage());
112 * Start the kie session
115 kieSession = startSession(
116 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
117 + "src/main/resources/__closedLoopControlName__.drl",
118 "src/test/resources/yaml/policy_ControlLoop_CCVPN.yaml", "type=operational", "Connectivity Reroute",
120 } catch (IOException e) {
122 logger.debug("Could not create kieSession");
123 fail("Could not create kieSession");
128 * Tear down the simulator.
131 public static void tearDownSimulator() {
134 * Gracefully shut down the kie session
136 kieSession.dispose();
138 PolicyEngine.manager.stop();
139 HttpServletServer.factory.destroy();
140 PolicyController.factory.shutdown();
141 TopicEndpoint.manager.shutdown();
145 public void successTest() throws IOException {
148 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
149 * to be pulled from the queue
151 for (TopicSink sink : noopTopics) {
152 assertTrue(sink.start());
157 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
160 sendEvent(pair.first);
162 kieSession.fireUntilHalt();
164 // allow object clean-up
165 kieSession.fireAllRules();
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 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
195 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
196 event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
197 event.setRequestId(UUID.randomUUID());
198 event.setClosedLoopEventClient("DCAE.HolmesInstance");
199 event.setTargetType(ControlLoopTargetType.VM);
200 event.setTarget("vserver.vserver-name");
201 event.setFrom("DCAE");
202 event.setClosedLoopAlarmStart(Instant.now());
203 event.setAai(new HashMap<String, String>());
204 event.getAai().put("vserver.vserver-name", "nullRequest");
205 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
206 kieSession.insert(event);
208 kieSession.fireUntilHalt();
210 // allow object clean-up
211 kieSession.fireAllRules();
214 * The only fact in memory should be Params
216 assertEquals(1, kieSession.getFactCount());
219 * Print what's left in memory
221 dumpFacts(kieSession);
225 * This method will start a kie session and instantiate the Policy Engine.
227 * @param droolsTemplate the DRL rules file
228 * @param yamlFile the yaml file containing the policies
229 * @param policyScope scope for policy
230 * @param policyName name of the policy
231 * @param policyVersion version of the policy
232 * @return the kieSession to be used to insert facts
233 * @throws IOException IO Exception
235 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
236 String policyName, String policyVersion) throws IOException {
239 * Load policies from yaml
241 pair = SupportUtil.loadYaml(yamlFile);
243 assertNotNull(pair.first);
244 assertNotNull(pair.first.getControlLoop());
245 assertNotNull(pair.first.getControlLoop().getControlLoopName());
246 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
249 * Construct a kie session
251 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
252 pair.first.getControlLoop().getControlLoopName(),
253 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
256 * Retrieve the Policy Engine
259 logger.debug("============");
260 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
261 logger.debug("============");
269 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
272 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
274 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
278 if ("POLICY-CL-MGT".equals(topic)) {
279 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
280 VirtualControlLoopNotification.class);
283 if (obj instanceof VirtualControlLoopNotification) {
284 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
285 String policyName = notification.getPolicyName();
286 if (policyName.endsWith("EVENT")) {
287 logger.debug("Rule Fired: " + notification.getPolicyName());
288 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
289 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
290 logger.debug("Rule Fired: " + notification.getPolicyName());
291 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
292 assertNotNull(notification.getMessage());
293 assertTrue(notification.getMessage().startsWith("Sending guard query"));
294 } else if (policyName.endsWith("GUARD.RESPONSE")) {
295 logger.debug("Rule Fired: " + notification.getPolicyName());
296 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
297 assertNotNull(notification.getMessage());
298 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
299 } else if (policyName.endsWith("GUARD_PERMITTED")) {
300 logger.debug("Rule Fired: " + notification.getPolicyName());
301 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
302 assertNotNull(notification.getMessage());
303 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
304 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
305 logger.debug("Rule Fired: " + notification.getPolicyName());
307 logger.debug("The operation timed out");
308 fail("Operation Timed Out");
309 } else if (policyName.endsWith("SDNC.RESPONSE")) {
310 logger.debug("Rule Fired: " + notification.getPolicyName());
311 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
312 assertNotNull(notification.getMessage());
313 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
314 } else if (policyName.endsWith("EVENT.MANAGER")) {
315 logger.debug("Rule Fired: " + notification.getPolicyName());
316 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
317 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
319 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
322 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
323 logger.debug("Rule Fired: " + notification.getPolicyName());
325 logger.debug("The control loop timed out");
326 fail("Control Loop Timed Out");
328 } else if (obj instanceof SdncRequest) {
329 logger.debug("\n============ SDNC received the request!!! ===========\n");
334 * This method is used to simulate event messages from DCAE that start the control loop (onset
335 * message) or end the control loop (abatement message).
337 * @param policy the controlLoopName comes from the policy
339 protected void sendEvent(ControlLoopPolicy policy) {
340 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
341 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
342 event.setRequestId(UUID.randomUUID());
343 event.setClosedLoopEventClient("DCAE.HolmesInstance");
344 event.setTargetType(ControlLoopTargetType.VM);
345 event.setTarget("vserver.vserver-name");
346 event.setFrom("DCAE");
347 event.setClosedLoopAlarmStart(Instant.now());
348 event.setAai(new HashMap<String, String>());
349 event.getAai().put("vserver.vserver-name", "TBD");
350 event.getAai().put("globalSubscriberId", "e151059a-d924-4629-845f-264db19e50b4");
351 event.getAai().put("serviceType", "SOTN");
352 event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
353 event.getAai().put("network-information.network-id", "id");
354 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
355 kieSession.insert(event);
359 * Dumps the kie session facts.
361 * @param kieSession input session
363 public static void dumpFacts(KieSession kieSession) {
364 logger.debug("Fact Count: " + kieSession.getFactCount());
365 for (FactHandle handle : kieSession.getFactHandles()) {
366 logger.debug("FACT: " + handle);