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 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
79 * Setup the simulator.
82 public static void setUpSimulator() {
83 PolicyEngine.manager.configure(new Properties());
84 assertTrue(PolicyEngine.manager.start());
85 Properties noopSinkProperties = new Properties();
86 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
87 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
88 "org.onap.policy.controlloop.VirtualControlLoopNotification");
89 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
90 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
91 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
93 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
94 .groupId("junit.groupId")
95 .artifactId("junit.artifactId")
96 .topic("POLICY-CL-MGT")
97 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
98 .protocolFilter(new JsonProtocolFilter())
99 .modelClassLoaderHash(1111));
102 SupportUtil.buildAaiSim();
103 SupportUtil.buildSdncSim();
104 } catch (Exception e) {
105 fail(e.getMessage());
110 * Start the kie session
113 kieSession = startSession(
114 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
115 + "src/main/resources/__closedLoopControlName__.drl",
116 "src/test/resources/yaml/policy_ControlLoop_CCVPN.yaml", "type=operational", "Connectivity Reroute",
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 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
158 sendEvent(pair.first);
160 kieSession.fireUntilHalt();
162 // allow object clean-up
163 kieSession.fireAllRules();
166 * The only fact in memory should be Params
168 assertEquals(1, kieSession.getFactCount());
171 * Print what's left in memory
173 dumpFacts(kieSession);
177 public void nullRequestTest() throws IOException {
180 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
181 * to be pulled from the queue
183 for (TopicSink sink : noopTopics) {
184 assertTrue(sink.start());
189 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
193 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
194 event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
195 event.setRequestId(UUID.randomUUID());
196 event.setClosedLoopEventClient("DCAE.HolmesInstance");
197 event.setTargetType(ControlLoopTargetType.VM);
198 event.setTarget("vserver.vserver-name");
199 event.setFrom("DCAE");
200 event.setClosedLoopAlarmStart(Instant.now());
201 event.setAai(new HashMap<String, String>());
202 event.getAai().put("vserver.vserver-name", "nullRequest");
203 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
204 kieSession.insert(event);
206 kieSession.fireUntilHalt();
208 // allow object clean-up
209 kieSession.fireAllRules();
212 * The only fact in memory should be Params
214 assertEquals(1, kieSession.getFactCount());
217 * Print what's left in memory
219 dumpFacts(kieSession);
223 * This method will start a kie session and instantiate the Policy Engine.
225 * @param droolsTemplate the DRL rules file
226 * @param yamlFile the yaml file containing the policies
227 * @param policyScope scope for policy
228 * @param policyName name of the policy
229 * @param policyVersion version of the policy
230 * @return the kieSession to be used to insert facts
231 * @throws IOException IO Exception
233 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
234 String policyName, String policyVersion) throws IOException {
237 * Load policies from yaml
239 pair = SupportUtil.loadYaml(yamlFile);
241 assertNotNull(pair.first);
242 assertNotNull(pair.first.getControlLoop());
243 assertNotNull(pair.first.getControlLoop().getControlLoopName());
244 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
247 * Construct a kie session
249 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
250 pair.first.getControlLoop().getControlLoopName(),
251 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
254 * Retrieve the Policy Engine
257 logger.debug("============");
258 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
259 logger.debug("============");
267 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
270 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
272 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
276 if ("POLICY-CL-MGT".equals(topic)) {
277 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
278 VirtualControlLoopNotification.class);
281 if (obj instanceof VirtualControlLoopNotification) {
282 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
283 String policyName = notification.getPolicyName();
284 if (policyName.endsWith("EVENT")) {
285 logger.debug("Rule Fired: " + notification.getPolicyName());
286 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
287 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
288 logger.debug("Rule Fired: " + notification.getPolicyName());
289 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
290 assertNotNull(notification.getMessage());
291 assertTrue(notification.getMessage().startsWith("Sending guard query"));
292 } else if (policyName.endsWith("GUARD.RESPONSE")) {
293 logger.debug("Rule Fired: " + notification.getPolicyName());
294 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
295 assertNotNull(notification.getMessage());
296 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
297 } else if (policyName.endsWith("GUARD_PERMITTED")) {
298 logger.debug("Rule Fired: " + notification.getPolicyName());
299 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
300 assertNotNull(notification.getMessage());
301 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
302 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
303 logger.debug("Rule Fired: " + notification.getPolicyName());
305 logger.debug("The operation timed out");
306 fail("Operation Timed Out");
307 } else if (policyName.endsWith("SDNC.RESPONSE")) {
308 logger.debug("Rule Fired: " + notification.getPolicyName());
309 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
310 assertNotNull(notification.getMessage());
311 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
312 } else if (policyName.endsWith("EVENT.MANAGER")) {
313 logger.debug("Rule Fired: " + notification.getPolicyName());
314 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
315 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
317 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
320 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
321 logger.debug("Rule Fired: " + notification.getPolicyName());
323 logger.debug("The control loop timed out");
324 fail("Control Loop Timed Out");
326 } else if (obj instanceof SdncRequest) {
327 logger.debug("\n============ SDNC received the request!!! ===========\n");
332 * This method is used to simulate event messages from DCAE that start the control loop (onset
333 * message) or end the control loop (abatement message).
335 * @param policy the controlLoopName comes from the policy
337 protected void sendEvent(ControlLoopPolicy policy) {
338 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
339 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
340 event.setRequestId(UUID.randomUUID());
341 event.setClosedLoopEventClient("DCAE.HolmesInstance");
342 event.setTargetType(ControlLoopTargetType.VM);
343 event.setTarget("vserver.vserver-name");
344 event.setFrom("DCAE");
345 event.setClosedLoopAlarmStart(Instant.now());
346 event.setAai(new HashMap<String, String>());
347 event.getAai().put("vserver.vserver-name", "TBD");
348 event.getAai().put("globalSubscriberId", "e151059a-d924-4629-845f-264db19e50b4");
349 event.getAai().put("serviceType", "SOTN");
350 event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
351 event.getAai().put("network-information.network-id", "id");
352 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
353 kieSession.insert(event);
357 * Dumps the kie session facts.
359 * @param kieSession input session
361 public static void dumpFacts(KieSession kieSession) {
362 logger.debug("Fact Count: " + kieSession.getFactCount());
363 for (FactHandle handle : kieSession.getFactHandles()) {
364 logger.debug("FACT: " + handle);