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();
 
 167         // allow object clean-up
 
 168         kieSession.fireAllRules();
 
 171          * The only fact in memory should be Params
 
 173         assertEquals(1, kieSession.getFactCount());
 
 176          * Print what's left in memory
 
 178         dumpFacts(kieSession);
 
 182     public void nullRequestTest() throws IOException {
 
 185          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
 
 186          * to be pulled from the queue
 
 188         for (TopicSink sink : noopTopics) {
 
 189             assertTrue(sink.start());
 
 194          * Create a unique requestId
 
 196         requestId = UUID.randomUUID();
 
 199          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
 
 203         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 204         event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
 
 205         event.setRequestId(UUID.randomUUID());
 
 206         event.setClosedLoopEventClient("tca.instance00009");
 
 207         event.setTargetType(ControlLoopTargetType.VM);
 
 208         event.setTarget("vserver.vserver-name");
 
 209         event.setFrom("DCAE");
 
 210         event.setClosedLoopAlarmStart(Instant.now());
 
 211         event.setAai(new HashMap<String, String>());
 
 212         event.getAai().put("vserver.vserver-name", "nullRequest");
 
 213         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
 
 214         kieSession.insert(event);
 
 216         kieSession.fireUntilHalt();
 
 218         // allow object clean-up
 
 219         kieSession.fireAllRules();
 
 222          * The only fact in memory should be Params
 
 224         assertEquals(1, kieSession.getFactCount());
 
 227          * Print what's left in memory
 
 229         dumpFacts(kieSession);
 
 233      * This method will start a kie session and instantiate the Policy Engine.
 
 235      * @param droolsTemplate the DRL rules file
 
 236      * @param yamlFile the yaml file containing the policies
 
 237      * @param policyScope scope for policy
 
 238      * @param policyName name of the policy
 
 239      * @param policyVersion version of the policy
 
 240      * @return the kieSession to be used to insert facts
 
 241      * @throws IOException IO Exception
 
 243     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
 
 244             String policyName, String policyVersion) throws IOException {
 
 247          * Load policies from yaml
 
 249         pair = Util.loadYaml(yamlFile);
 
 251         assertNotNull(pair.first);
 
 252         assertNotNull(pair.first.getControlLoop());
 
 253         assertNotNull(pair.first.getControlLoop().getControlLoopName());
 
 254         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
 
 257          * Construct a kie session
 
 259         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
 
 260                 pair.first.getControlLoop().getControlLoopName(),
 
 261                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
 
 264          * Retrieve the Policy Engine
 
 267         logger.debug("============");
 
 268         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
 
 269         logger.debug("============");
 
 277      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
 
 280     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
 
 282          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
 
 286         if ("POLICY-CL-MGT".equals(topic)) {
 
 287             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
 
 288                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
 
 291         if (obj instanceof VirtualControlLoopNotification) {
 
 292             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
 
 293             String policyName = notification.getPolicyName();
 
 294             if (policyName.endsWith("EVENT")) {
 
 295                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 296                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
 
 297             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
 
 298                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 299                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 300                 assertNotNull(notification.getMessage());
 
 301                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
 
 302             } else if (policyName.endsWith("GUARD.RESPONSE")) {
 
 303                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 304                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 305                 assertNotNull(notification.getMessage());
 
 306                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
 
 307             } else if (policyName.endsWith("GUARD_PERMITTED")) {
 
 308                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 309                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 310                 assertNotNull(notification.getMessage());
 
 311                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
 
 312             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
 
 313                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 315                 logger.debug("The operation timed out");
 
 316                 fail("Operation Timed Out");
 
 317             } else if (policyName.endsWith("VFC.RESPONSE")) {
 
 318                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 319                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
 
 320                 assertNotNull(notification.getMessage());
 
 321                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
 
 322             } else if (policyName.endsWith("EVENT.MANAGER")) {
 
 323                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 324                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
 
 325                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
 
 327                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
 
 330             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
 
 331                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 333                 logger.debug("The control loop timed out");
 
 334                 fail("Control Loop Timed Out");
 
 336         } else if (obj instanceof VFCRequest) {
 
 337             logger.debug("\n============ VFC received the request!!! ===========\n");
 
 342      * This method is used to simulate event messages from DCAE that start the control loop (onset
 
 343      * message) or end the control loop (abatement message).
 
 345      * @param policy the controlLoopName comes from the policy
 
 346      * @param requestID the requestId for this event
 
 347      * @param status could be onset or abated
 
 349     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
 
 350         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 351         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
 
 352         event.setRequestId(UUID.randomUUID());
 
 353         event.setClosedLoopEventClient("tca.instance00009");
 
 354         event.setTargetType(ControlLoopTargetType.VM);
 
 355         event.setTarget("vserver.vserver-name");
 
 356         event.setFrom("DCAE");
 
 357         event.setClosedLoopAlarmStart(Instant.now());
 
 358         event.setAai(new HashMap<String, String>());
 
 359         event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
 
 360         event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
 
 361         event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
 
 362         event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
 
 363         event.getAai().put("vserver.is-closed-loop-disabled", "false");
 
 364         event.getAai().put("vserver.prov-status", "ACTIVE");
 
 365         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
 
 366         kieSession.insert(event);
 
 370      * Dumps the kie session facts.
 
 372      * @param kieSession input session
 
 374     public static void dumpFacts(KieSession kieSession) {
 
 375         logger.debug("Fact Count: " + kieSession.getFactCount());
 
 376         for (FactHandle handle : kieSession.getFactHandles()) {
 
 377             logger.debug("FACT: " + handle);