2  * ============LICENSE_START=======================================================
 
   3  * Copyright (C) 2018 Huawei. All rights reserved.
 
   4  * ================================================================================
 
   5  * Licensed under the Apache License, Version 2.0 (the "License");
 
   6  * you may not use this file except in compliance with the License.
 
   7  * You may obtain a copy of the License at
 
   9  *      http://www.apache.org/licenses/LICENSE-2.0
 
  11  * Unless required by applicable law or agreed to in writing, software
 
  12  * distributed under the License is distributed on an "AS IS" BASIS,
 
  13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  14  * See the License for the specific language governing permissions and
 
  15  * limitations under the License.
 
  16  * ============LICENSE_END=========================================================
 
  19 package org.onap.policy.template.demo;
 
  21 import static org.junit.Assert.assertEquals;
 
  22 import static org.junit.Assert.assertNotNull;
 
  23 import static org.junit.Assert.assertTrue;
 
  24 import static org.junit.Assert.fail;
 
  26 import java.io.IOException;
 
  27 import java.net.URLEncoder;
 
  28 import java.time.Instant;
 
  29 import java.util.HashMap;
 
  30 import java.util.List;
 
  31 import java.util.Properties;
 
  32 import java.util.UUID;
 
  34 import org.junit.AfterClass;
 
  35 import org.junit.BeforeClass;
 
  36 import org.junit.Test;
 
  37 import org.kie.api.runtime.KieSession;
 
  38 import org.kie.api.runtime.rule.FactHandle;
 
  39 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
 
  40 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
 
  41 import org.onap.policy.common.endpoints.event.comm.TopicListener;
 
  42 import org.onap.policy.common.endpoints.event.comm.TopicSink;
 
  43 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
 
  44 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 
  45 import org.onap.policy.controlloop.ControlLoopEventStatus;
 
  46 import org.onap.policy.controlloop.ControlLoopNotificationType;
 
  47 import org.onap.policy.controlloop.ControlLoopTargetType;
 
  48 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  49 import org.onap.policy.controlloop.VirtualControlLoopNotification;
 
  50 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 
  51 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
 
  52 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
 
  53 import org.onap.policy.drools.system.PolicyController;
 
  54 import org.onap.policy.drools.system.PolicyEngine;
 
  55 import org.onap.policy.drools.utils.logging.LoggerUtil;
 
  56 import org.onap.policy.sdnc.SdncRequest;
 
  57 import org.slf4j.Logger;
 
  58 import org.slf4j.LoggerFactory;
 
  60 public class CcvpnControlLoopTest implements TopicListener {
 
  62     private static final Logger logger = LoggerFactory.getLogger(CcvpnControlLoopTest.class);
 
  64     private static List<? extends TopicSink> noopTopics;
 
  66     private static KieSession kieSession;
 
  67     private static Util.Pair<ControlLoopPolicy, String> pair;
 
  70         /* Set environment properties */
 
  73         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
 
  77      * Setup the simulator.
 
  80     public static void setUpSimulator() {
 
  81         PolicyEngine.manager.configure(new Properties());
 
  82         assertTrue(PolicyEngine.manager.start());
 
  83         Properties noopSinkProperties = new Properties();
 
  84         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
 
  85         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
 
  86                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
 
  87         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
 
  88                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
 
  89         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
 
  91         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
 
  92                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(),
 
  98         } catch (Exception e) {
 
 104          * Start the kie session
 
 107             kieSession = startSession(
 
 108                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
 
 109                     + "src/main/resources/__closedLoopControlName__.drl",
 
 110                     "src/test/resources/yaml/policy_ControlLoop_CCVPN.yaml", "type=operational", "Connectivity Reroute",
 
 112         } catch (IOException e) {
 
 114             logger.debug("Could not create kieSession");
 
 115             fail("Could not create kieSession");
 
 120      * Tear down the simulator.
 
 123     public static void tearDownSimulator() {
 
 126          * Gracefully shut down the kie session
 
 128         kieSession.dispose();
 
 130         PolicyEngine.manager.stop();
 
 131         HttpServletServer.factory.destroy();
 
 132         PolicyController.factory.shutdown();
 
 133         TopicEndpoint.manager.shutdown();
 
 137     public void successTest() throws IOException {
 
 140          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
 
 141          * to be pulled from the queue
 
 143         for (TopicSink sink : noopTopics) {
 
 144             assertTrue(sink.start());
 
 149          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
 
 152         sendEvent(pair.first);
 
 154         kieSession.fireUntilHalt();
 
 156         // allow object clean-up
 
 157         kieSession.fireAllRules();
 
 160          * The only fact in memory should be Params
 
 162         assertEquals(1, kieSession.getFactCount());
 
 165          * Print what's left in memory
 
 167         dumpFacts(kieSession);
 
 171     public void nullRequestTest() throws IOException {
 
 174          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
 
 175          * to be pulled from the queue
 
 177         for (TopicSink sink : noopTopics) {
 
 178             assertTrue(sink.start());
 
 183          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
 
 187         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 188         event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
 
 189         event.setRequestId(UUID.randomUUID());
 
 190         event.setClosedLoopEventClient("DCAE.HolmesInstance");
 
 191         event.setTargetType(ControlLoopTargetType.VM);
 
 192         event.setTarget("vserver.vserver-name");
 
 193         event.setFrom("DCAE");
 
 194         event.setClosedLoopAlarmStart(Instant.now());
 
 195         event.setAai(new HashMap<String, String>());
 
 196         event.getAai().put("vserver.vserver-name", "nullRequest");
 
 197         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
 
 198         kieSession.insert(event);
 
 200         kieSession.fireUntilHalt();
 
 202         // allow object clean-up
 
 203         kieSession.fireAllRules();
 
 206          * The only fact in memory should be Params
 
 208         assertEquals(1, kieSession.getFactCount());
 
 211          * Print what's left in memory
 
 213         dumpFacts(kieSession);
 
 217      * This method will start a kie session and instantiate the Policy Engine.
 
 219      * @param droolsTemplate the DRL rules file
 
 220      * @param yamlFile the yaml file containing the policies
 
 221      * @param policyScope scope for policy
 
 222      * @param policyName name of the policy
 
 223      * @param policyVersion version of the policy
 
 224      * @return the kieSession to be used to insert facts
 
 225      * @throws IOException IO Exception
 
 227     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
 
 228             String policyName, String policyVersion) throws IOException {
 
 231          * Load policies from yaml
 
 233         pair = Util.loadYaml(yamlFile);
 
 235         assertNotNull(pair.first);
 
 236         assertNotNull(pair.first.getControlLoop());
 
 237         assertNotNull(pair.first.getControlLoop().getControlLoopName());
 
 238         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
 
 241          * Construct a kie session
 
 243         final KieSession kieSession = Util.buildContainer(droolsTemplate,
 
 244                 pair.first.getControlLoop().getControlLoopName(),
 
 245                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
 
 248          * Retrieve the Policy Engine
 
 251         logger.debug("============");
 
 252         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
 
 253         logger.debug("============");
 
 261      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
 
 264     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
 
 266          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
 
 270         if ("POLICY-CL-MGT".equals(topic)) {
 
 271             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
 
 272                     VirtualControlLoopNotification.class);
 
 275         if (obj instanceof VirtualControlLoopNotification) {
 
 276             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
 
 277             String policyName = notification.getPolicyName();
 
 278             if (policyName.endsWith("EVENT")) {
 
 279                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 280                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
 
 281             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
 
 282                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 283                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 284                 assertNotNull(notification.getMessage());
 
 285                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
 
 286             } else if (policyName.endsWith("GUARD.RESPONSE")) {
 
 287                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 288                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 289                 assertNotNull(notification.getMessage());
 
 290                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
 
 291             } else if (policyName.endsWith("GUARD_PERMITTED")) {
 
 292                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 293                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 294                 assertNotNull(notification.getMessage());
 
 295                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
 
 296             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
 
 297                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 299                 logger.debug("The operation timed out");
 
 300                 fail("Operation Timed Out");
 
 301             } else if (policyName.endsWith("SDNC.RESPONSE")) {
 
 302                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 303                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
 
 304                 assertNotNull(notification.getMessage());
 
 305                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
 
 306             } else if (policyName.endsWith("EVENT.MANAGER")) {
 
 307                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 308                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
 
 309                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
 
 311                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
 
 314             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
 
 315                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 317                 logger.debug("The control loop timed out");
 
 318                 fail("Control Loop Timed Out");
 
 320         } else if (obj instanceof SdncRequest) {
 
 321             logger.debug("\n============ SDNC received the request!!! ===========\n");
 
 326      * This method is used to simulate event messages from DCAE that start the control loop (onset
 
 327      * message) or end the control loop (abatement message).
 
 329      * @param policy the controlLoopName comes from the policy
 
 331     protected void sendEvent(ControlLoopPolicy policy) {
 
 332         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 333         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
 
 334         event.setRequestId(UUID.randomUUID());
 
 335         event.setClosedLoopEventClient("DCAE.HolmesInstance");
 
 336         event.setTargetType(ControlLoopTargetType.VM);
 
 337         event.setTarget("vserver.vserver-name");
 
 338         event.setFrom("DCAE");
 
 339         event.setClosedLoopAlarmStart(Instant.now());
 
 340         event.setAai(new HashMap<String, String>());
 
 341         event.getAai().put("vserver.vserver-name", "TBD");
 
 342         event.getAai().put("globalSubscriberId", "e151059a-d924-4629-845f-264db19e50b4");
 
 343         event.getAai().put("serviceType", "SOTN");
 
 344         event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
 
 345         event.getAai().put("network-information.network-id", "id");
 
 346         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
 
 347         kieSession.insert(event);
 
 351      * Dumps the kie session facts.
 
 353      * @param kieSession input session
 
 355     public static void dumpFacts(KieSession kieSession) {
 
 356         logger.debug("Fact Count: " + kieSession.getFactCount());
 
 357         for (FactHandle handle : kieSession.getFactHandles()) {
 
 358             logger.debug("FACT: " + handle);