2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Licensed under the Apache License, Version 2.0 (the "License");
 
   8  * you may not use this file except in compliance with the License.
 
   9  * You may obtain a copy of the License at
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  18  * ============LICENSE_END=========================================================
 
  21 package org.onap.policy.template.demo;
 
  23 import static org.junit.Assert.assertEquals;
 
  24 import static org.junit.Assert.assertNotNull;
 
  25 import static org.junit.Assert.assertTrue;
 
  26 import static org.junit.Assert.fail;
 
  28 import java.io.IOException;
 
  29 import java.net.URLEncoder;
 
  30 import java.time.Instant;
 
  31 import java.util.HashMap;
 
  32 import java.util.List;
 
  33 import java.util.Properties;
 
  34 import java.util.UUID;
 
  36 import org.junit.AfterClass;
 
  37 import org.junit.BeforeClass;
 
  38 import org.junit.Test;
 
  39 import org.kie.api.runtime.KieSession;
 
  40 import org.kie.api.runtime.rule.FactHandle;
 
  41 import org.onap.policy.appc.Request;
 
  42 import org.onap.policy.appc.Response;
 
  43 import org.onap.policy.appc.ResponseCode;
 
  44 import org.onap.policy.controlloop.ControlLoopEventStatus;
 
  45 import org.onap.policy.controlloop.ControlLoopNotificationType;
 
  46 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  47 import org.onap.policy.controlloop.VirtualControlLoopNotification;
 
  48 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 
  49 import org.onap.policy.drools.event.comm.TopicEndpoint;
 
  50 import org.onap.policy.drools.event.comm.TopicListener;
 
  51 import org.onap.policy.drools.event.comm.TopicSink;
 
  52 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
 
  53 import org.onap.policy.drools.http.server.HttpServletServer;
 
  54 import org.onap.policy.drools.properties.PolicyProperties;
 
  55 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
 
  56 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
 
  57 import org.onap.policy.drools.system.PolicyEngine;
 
  58 import org.slf4j.Logger;
 
  59 import org.slf4j.LoggerFactory;
 
  61 public class VFWControlLoopTest implements TopicListener {
 
  63     private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
 
  65     private static List<? extends TopicSink> noopTopics;
 
  67     private static KieSession kieSession;
 
  68     private static Util.Pair<ControlLoopPolicy, String> pair;
 
  69     private UUID requestID;
 
  72         /* Set environment properties */
 
  79     public static void setUpSimulator() {
 
  80         PolicyEngine.manager.configure(new Properties());
 
  81         assertTrue(PolicyEngine.manager.start());
 
  82         Properties noopSinkProperties = new Properties();
 
  83         noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
 
  84         noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
 
  85         noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", "org.onap.policy.appc.util.Serialization,gsonPretty");
 
  86         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
 
  87         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
 
  88         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
 
  90         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
 
  91         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111);
 
  96         } catch (Exception e) {
 
 101          * Start the kie session
 
 104             kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", 
 
 105                         "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
 
 106                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
 
 108                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
 
 109         } catch (IOException e) {
 
 111             logger.debug("Could not create kieSession");
 
 112             fail("Could not create kieSession");
 
 117     public static void tearDownSimulator() {
 
 119          * Gracefully shut down the kie session
 
 121         kieSession.dispose();
 
 123         HttpServletServer.factory.destroy();
 
 124         PolicyEngine.manager.shutdown();
 
 125         TopicEndpoint.manager.shutdown();
 
 126         PolicyEngine.manager.stop();
 
 130     public void successTest() {
 
 133          * Allows the PolicyEngine to callback to this object to
 
 134          * notify that there is an event ready to be pulled 
 
 137         for (TopicSink sink : noopTopics) {
 
 138             assertTrue(sink.start());
 
 143          * Create a unique requestId
 
 145         requestID = UUID.randomUUID();
 
 148          * Simulate an onset event the policy engine will 
 
 149          * receive from DCAE to kick off processing through
 
 152         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
 
 155                 kieSession.fireUntilHalt();
 
 157         catch (Exception e) {
 
 159                 logger.warn(e.toString());
 
 165          * The only fact in memory should be Params
 
 167         assertEquals(1, kieSession.getFactCount());
 
 170          * Print what's left in memory
 
 172         dumpFacts(kieSession);
 
 176     public void aaiFailTests() {
 
 179          * Allows the PolicyEngine to callback to this object to
 
 180          * notify that there is an event ready to be pulled 
 
 183         for (TopicSink sink : noopTopics) {
 
 184             assertTrue(sink.start());
 
 189          * Create a unique requestId
 
 191         requestID = UUID.randomUUID();
 
 194          * Simulate an onset event the policy engine will 
 
 195          * receive from DCAE to kick off processing through
 
 198         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error");
 
 200                 kieSession.fireUntilHalt();
 
 202         catch (Exception e) {
 
 204                 logger.warn(e.toString());
 
 205                 fail(e.getMessage());
 
 209          * The only fact in memory should be Params
 
 211         assertEquals(1, kieSession.getFactCount());
 
 214          * Print what's left in memory
 
 216         dumpFacts(kieSession);
 
 219          * Create a unique requestId
 
 221         requestID = UUID.randomUUID();
 
 224          * Simulate an onset event the policy engine will 
 
 225          * receive from DCAE to kick off processing through
 
 229         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
 
 232                 kieSession.fireUntilHalt();
 
 234         catch (Exception e) {
 
 236                 logger.warn(e.toString());
 
 237                 fail(e.getMessage());
 
 241          * The only fact in memory should be Params
 
 243         assertEquals(1, kieSession.getFactCount());
 
 246          * Print what's left in memory
 
 248         dumpFacts(kieSession);
 
 252      * This method will start a kie session and instantiate 
 
 255      * @param droolsTemplate
 
 258      *          the yaml file containing the policies
 
 263      * @param policyVersion
 
 264      *          version of the policy          
 
 265      * @return the kieSession to be used to insert facts 
 
 266      * @throws IOException
 
 268     private static KieSession startSession(String droolsTemplate, 
 
 272             String policyVersion) throws IOException {
 
 275          * Load policies from yaml
 
 277         pair = Util.loadYaml(yamlFile);
 
 279         assertNotNull(pair.a);
 
 280         assertNotNull(pair.a.getControlLoop());
 
 281         assertNotNull(pair.a.getControlLoop().getControlLoopName());
 
 282         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
 
 285          * Construct a kie session
 
 287         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
 
 288                 pair.a.getControlLoop().getControlLoopName(), 
 
 292                 URLEncoder.encode(pair.b, "UTF-8"));
 
 295          * Retrieve the Policy Engine
 
 298         logger.debug("============");
 
 299         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
 
 300         logger.debug("============");
 
 306      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
 
 308     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
 
 310          * Pull the object that was sent out to DMAAP and make
 
 311          * sure it is a ControlLoopNoticiation of type active
 
 314         if ("POLICY-CL-MGT".equals(topic)) {
 
 315                 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
 
 317         else if ("APPC-CL".equals(topic))
 
 318                 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, org.onap.policy.appc.Request.class);
 
 320         if (obj instanceof VirtualControlLoopNotification) {
 
 321             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
 
 322             String policyName = notification.policyName;
 
 323             if (policyName.endsWith("EVENT")) {
 
 324                 logger.debug("Rule Fired: " + notification.policyName);
 
 325                 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-id"))) {
 
 326                         assertEquals(ControlLoopNotificationType.REJECTED, notification.notification);
 
 330                     assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
 
 333             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
 
 334                 logger.debug("Rule Fired: " + notification.policyName);
 
 335                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
 
 336                 assertNotNull(notification.message);
 
 337                 assertTrue(notification.message.startsWith("Sending guard query"));
 
 339             else if (policyName.endsWith("GUARD.RESPONSE")) {
 
 340                 logger.debug("Rule Fired: " + notification.policyName);
 
 341                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
 
 342                 assertNotNull(notification.message);
 
 343                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
 
 345             else if (policyName.endsWith("GUARD_PERMITTED")) {
 
 346                 logger.debug("Rule Fired: " + notification.policyName);
 
 347                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
 
 348                 assertNotNull(notification.message);
 
 349                 assertTrue(notification.message.startsWith("actor=APPC"));
 
 351             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
 
 352                 logger.debug("Rule Fired: " + notification.policyName);
 
 354                 logger.debug("The operation timed out");
 
 355                 fail("Operation Timed Out");
 
 357             else if (policyName.endsWith("APPC.RESPONSE")) {
 
 358                 logger.debug("Rule Fired: " + notification.policyName);
 
 359                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
 
 360                 assertNotNull(notification.message);
 
 361                 assertTrue(notification.message.startsWith("actor=APPC"));
 
 362                 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
 
 364             else if (policyName.endsWith("EVENT.MANAGER")) {
 
 365                 logger.debug("Rule Fired: " + notification.policyName);
 
 366                 if ("error".equals(notification.AAI.get("generic-vnf.vnf-id"))) {
 
 367                         assertTrue(ControlLoopNotificationType.FINAL_FAILURE.equals(notification.notification));
 
 368                         assertEquals("Exception in processing closed loop", notification.message);
 
 371                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
 
 375             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
 
 376                 logger.debug("Rule Fired: " + notification.policyName);
 
 378                 logger.debug("The control loop timed out");
 
 379                 fail("Control Loop Timed Out");
 
 382         else if (obj instanceof Request) {
 
 383             assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
 
 385             logger.debug("\n============ APPC received the request!!! ===========\n");
 
 388              * Simulate a success response from APPC and insert
 
 389              * the response into the working memory
 
 391             Response appcResponse = new Response((Request)obj);
 
 392             appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
 
 393             appcResponse.getStatus().Value = "SUCCESS";
 
 394             kieSession.insert(appcResponse);
 
 399      * This method is used to simulate event messages from DCAE
 
 400      * that start the control loop (onset message) or end the
 
 401      * control loop (abatement message).
 
 403      * @param policy the controlLoopName comes from the policy 
 
 404      * @param requestID the requestId for this event
 
 405      * @param status could be onset or abated
 
 407     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
 
 408         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 409         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
 
 410         event.requestID = requestID;
 
 411         event.target = "generic-vnf.vnf-id";
 
 412         event.closedLoopAlarmStart = Instant.now();
 
 413         event.AAI = new HashMap<>();
 
 414         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
 
 415         event.closedLoopEventStatus = status;
 
 416         kieSession.insert(event);
 
 420      * This method is used to simulate event messages from DCAE
 
 421      * that start the control loop (onset message) or end the
 
 422      * control loop (abatement message).
 
 424      * @param policy the controlLoopName comes from the policy 
 
 425      * @param requestID the requestId for this event
 
 426      * @param status could be onset or abated
 
 428     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfId) {
 
 429         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 430         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
 
 431         event.requestID = requestID;
 
 432         event.target = "generic-vnf.vnf-id";
 
 433         event.closedLoopAlarmStart = Instant.now();
 
 434         event.AAI = new HashMap<>();
 
 435         event.AAI.put("generic-vnf.vnf-id", vnfId);
 
 436         event.closedLoopEventStatus = status;
 
 437         kieSession.insert(event);
 
 441      * This method will dump all the facts in the working memory.
 
 443      * @param kieSession the session containing the facts
 
 445     public void dumpFacts(KieSession kieSession) {
 
 446         logger.debug("Fact Count: {}", kieSession.getFactCount());
 
 447         for (FactHandle handle : kieSession.getFactHandles()) {
 
 448             logger.debug("FACT: {}", handle);