2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2018 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.clc;
 
  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 com.google.gson.Gson;
 
  30 import java.io.IOException;
 
  31 import java.lang.StringBuilder;
 
  32 import java.net.URLEncoder;
 
  33 import java.time.Instant;
 
  34 import java.util.HashMap;
 
  35 import java.util.List;
 
  36 import java.util.Properties;
 
  37 import java.util.UUID;
 
  39 import org.junit.AfterClass;
 
  40 import org.junit.BeforeClass;
 
  41 import org.junit.Test;
 
  43 import org.kie.api.runtime.KieSession;
 
  44 import org.kie.api.runtime.rule.FactHandle;
 
  46 import org.onap.policy.appclcm.LcmRequest;
 
  47 import org.onap.policy.appclcm.LcmRequestWrapper;
 
  48 import org.onap.policy.appclcm.LcmResponse;
 
  49 import org.onap.policy.appclcm.LcmResponseWrapper;
 
  50 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
 
  51 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
 
  52 import org.onap.policy.common.endpoints.event.comm.TopicListener;
 
  53 import org.onap.policy.common.endpoints.event.comm.TopicSink;
 
  54 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
 
  55 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 
  56 import org.onap.policy.controlloop.ControlLoopEventStatus;
 
  57 import org.onap.policy.controlloop.ControlLoopNotificationType;
 
  58 import org.onap.policy.controlloop.ControlLoopTargetType;
 
  59 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  60 import org.onap.policy.controlloop.VirtualControlLoopNotification;
 
  61 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 
  62 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
 
  63 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
 
  64 import org.onap.policy.drools.system.PolicyController;
 
  65 import org.onap.policy.drools.system.PolicyEngine;
 
  67 import org.slf4j.Logger;
 
  68 import org.slf4j.LoggerFactory;
 
  70 public class ControlLoopCoordinationTest implements TopicListener {
 
  72     private static final Logger logger = LoggerFactory.getLogger(ControlLoopCoordinationTest.class);
 
  74     private static List<? extends TopicSink> noopTopics;
 
  76     private static KieSession kieSession1;
 
  77     private static KieSession kieSession2;
 
  78     private static StringBuilder controlLoopOneName = new StringBuilder();
 
  79     private static StringBuilder controlLoopTwoName = new StringBuilder();
 
  80     private static String expectedDecision;
 
  83         /* Set environment properties */
 
  85         Util.setGuardPropsEmbedded();
 
  93     public static void setUpSimulator() {
 
  94         PolicyEngine.manager.configure(new Properties());
 
  95         assertTrue(PolicyEngine.manager.start());
 
  96         Properties noopSinkProperties = new Properties();
 
  97         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
 
  98         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
 
  99         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
 
 100                 "org.onap.policy.appclcm.util.Serialization,gson");
 
 101         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
 
 102                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
 
 103         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
 
 104                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
 
 105         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
 
 107         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
 
 108                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
 
 110         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ",
 
 111                 "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
 
 114         } catch (Exception e) {
 
 115             fail(e.getMessage());
 
 119          * Start the kie sessions
 
 122             kieSession1 = startSession(
 
 124                     "src/main/resources/__closedLoopControlName__.drl",
 
 125                     "src/test/resources/yaml/policy_ControlLoop_SyntheticOne.yaml",
 
 126                     "service=ServiceDemo;resource=Res1Demo;type=operational",
 
 127                     "SyntheticControlLoopOnePolicy",
 
 128                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
 
 129             kieSession2 = startSession(
 
 131                     "src/main/resources/__closedLoopControlName__.drl",
 
 132                     "src/test/resources/yaml/policy_ControlLoop_SyntheticTwo.yaml",
 
 133                     "service=ServiceDemo;resource=Res1Demo;type=operational",
 
 134                     "SyntheticControlLoopTwoPolicy",
 
 135                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
 
 136         } catch (IOException e) {
 
 137             logger.debug("Could not create kieSession, exception {}", e.getMessage());
 
 138             fail("Could not create kieSession");
 
 143      * Tear down simulator.
 
 146     public static void tearDownSimulator() {
 
 148          * Gracefully shut down the kie session
 
 150         kieSession1.dispose();
 
 151         kieSession2.dispose();
 
 153         PolicyEngine.manager.stop();
 
 154         HttpServletServer.factory.destroy();
 
 155         PolicyController.factory.shutdown();
 
 156         TopicEndpoint.manager.shutdown();
 
 160      * Set expected decision.
 
 162      * @param ed the expected decision ("PERMIT" or "DENY")
 
 164     public void expectedDecisionIs(String ed) {
 
 165         expectedDecision = ed;
 
 166         logger.info("Expected decision is {}", ed);
 
 170      * This method is used to simulate event messages from DCAE
 
 171      * that start the control loop (onset message) or end the
 
 172      * control loop (abatement message).
 
 174      * @param controlLoopName the control loop name
 
 175      * @param requestID the requestId for this event
 
 176      * @param status could be onset or abated
 
 177      * @param target the target name
 
 178      * @param kieSession the kieSession to which this event is being sent
 
 180     protected void sendEvent(String controlLoopName,
 
 182                              ControlLoopEventStatus status,
 
 184                              KieSession kieSession) {
 
 185         logger.debug("sendEvent controlLoopName={}", controlLoopName);
 
 186         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 187         event.setClosedLoopControlName(controlLoopName);
 
 188         event.setRequestId(requestId);
 
 189         event.setTarget("generic-vnf.vnf-name");
 
 190         event.setTargetType(ControlLoopTargetType.VNF);
 
 191         event.setClosedLoopAlarmStart(Instant.now());
 
 192         event.setAai(new HashMap<>());
 
 193         event.getAai().put("generic-vnf.vnf-name", target);
 
 194         event.setClosedLoopEventStatus(status);
 
 196         Gson gson = new Gson();
 
 197         String json = gson.toJson(event);
 
 198         logger.debug("sendEvent {}", json);
 
 200         kieSession.insert(event);
 
 205      * Simulate an event by inserting into kieSession and firing rules as needed.
 
 207      * @param cles the ControlLoopEventStatus
 
 208      * @param rid the request ID
 
 209      * @param controlLoopName the control loop name
 
 210      * @param kieSession the kieSession to which this event is being sent
 
 211      * @param expectedDecision the expected decision
 
 213     protected void simulateEvent(ControlLoopEventStatus cles,
 
 215                                  String controlLoopName,
 
 217                                  KieSession kieSession,
 
 218                                  String expectedDecision) {
 
 220         // if onset, set expected decision
 
 222         if (cles == ControlLoopEventStatus.ONSET) {
 
 223             expectedDecisionIs(expectedDecision);
 
 226         // simulate sending event
 
 228         sendEvent(controlLoopName, rid, cles, target, kieSession);
 
 229         kieSession.fireUntilHalt();
 
 231         // get dump of database entries and log
 
 233         List<?> entries = Util.dumpDb();
 
 234         assertNotNull(entries);
 
 235         logger.debug("dumpDB, {} entries", entries.size());
 
 236         for (Object entry : entries) {
 
 237             logger.debug("{}", entry);
 
 242         logger.info("simulateEvent: done");
 
 246      * Simulate an onset event.
 
 248      * @param rid the request ID
 
 249      * @param controlLoopName the control loop name
 
 250      * @param kieSession the kieSession to which this event is being sent
 
 251      * @param expectedDecision the expected decision 
 
 253     public void simulateOnset(UUID rid,
 
 254                               String controlLoopName,
 
 256                               KieSession kieSession,
 
 257                               String expectedDecision) {
 
 258         simulateEvent(ControlLoopEventStatus.ONSET, rid, controlLoopName, target, kieSession, expectedDecision);
 
 262      * Simulate an abated event.
 
 264      * @param rid the request ID
 
 265      * @param controlLoopName the control loop name
 
 266      * @param kieSession the kieSession to which this event is being sent
 
 268     public void simulateAbatement(UUID rid,
 
 269                                   String controlLoopName,
 
 271                                   KieSession kieSession) {
 
 272         simulateEvent(ControlLoopEventStatus.ABATED, rid, controlLoopName, target, kieSession, null);
 
 276      * This method will start a kie session and instantiate the Policy Engine.
 
 278      * @param droolsTemplate the DRL rules file
 
 279      * @param yamlFile the yaml file containing the policies
 
 280      * @param policyScope scope for policy
 
 281      * @param policyName name of the policy
 
 282      * @param policyVersion version of the policy
 
 283      * @return the kieSession to be used to insert facts
 
 284      * @throws IOException throws IO exception
 
 286     private static KieSession startSession(StringBuilder controlLoopName,
 
 287                                            String droolsTemplate,
 
 291                                            String policyVersion) throws IOException {
 
 294          * Load policies from yaml
 
 296         Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml(yamlFile);
 
 298         assertNotNull(pair.first);
 
 299         assertNotNull(pair.first.getControlLoop());
 
 300         assertNotNull(pair.first.getControlLoop().getControlLoopName());
 
 301         assertTrue(!pair.first.getControlLoop().getControlLoopName().isEmpty());
 
 303         controlLoopName.append(pair.first.getControlLoop().getControlLoopName());
 
 304         String yamlContents = pair.second;
 
 307          * Construct a kie session
 
 309         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
 
 310                                                           controlLoopName.toString(),
 
 314                                                           URLEncoder.encode(yamlContents, "UTF-8"));
 
 317          * Retrieve the Policy Engine
 
 320         logger.debug("============");
 
 321         logger.debug(URLEncoder.encode(yamlContents, "UTF-8"));
 
 322         logger.debug("============");
 
 330      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
 
 333     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
 
 335          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
 
 339         if ("POLICY-CL-MGT".equals(topic)) {
 
 340             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
 
 341                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
 
 342         } else if ("APPC-LCM-READ".equals(topic)) {
 
 343             obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
 
 344                     org.onap.policy.appclcm.LcmRequestWrapper.class);
 
 347         if (obj instanceof VirtualControlLoopNotification) {
 
 348             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
 
 349             String policyName = notification.getPolicyName();
 
 350             if (policyName.endsWith("EVENT")) {
 
 351                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 352                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
 
 353             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
 
 354                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 355                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 356                 assertNotNull(notification.getMessage());
 
 357                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
 
 358             } else if (policyName.endsWith("GUARD.RESPONSE")) {
 
 359                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 360                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 361                 assertNotNull(notification.getMessage());
 
 362                 // THESE ARE THE MOST CRITICAL ASSERTS
 
 363                 // TEST IF GUARD.RESPONSE IS CORRECT
 
 364                 logger.debug("Testing whether decision was {} as expected", expectedDecision);
 
 365                 assertTrue(notification.getMessage().toUpperCase().endsWith(expectedDecision));
 
 366             } else if (policyName.endsWith("GUARD_PERMITTED")) {
 
 367                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 368                 assertEquals(ControlLoopNotificationType.OPERATION,notification.getNotification());
 
 369                 assertNotNull(notification.getMessage());
 
 370                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
 
 371             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
 
 372                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 375                 logger.debug("The operation timed out");
 
 376                 fail("Operation Timed Out");
 
 377             } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
 
 378                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 379                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
 
 380                 assertNotNull(notification.getMessage());
 
 381                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
 
 382             } else if (policyName.endsWith("EVENT.MANAGER")) {
 
 383                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 384                 if (notification.getMessage().endsWith("Closing the control loop.")
 
 385                     || notification.getMessage().equals("Waiting for abatement")) {
 
 386                     if (policyName.startsWith(controlLoopOneName.toString())) {
 
 387                         logger.debug("Halting kieSession1");
 
 389                     } else if (policyName.startsWith(controlLoopTwoName.toString())) {
 
 390                         logger.debug("Halting kieSession2");
 
 393                         fail("Unknown ControlLoop"); 
 
 396             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
 
 397                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 400                 logger.debug("The control loop timed out");
 
 401                 fail("Control Loop Timed Out");
 
 403         } else if (obj instanceof LcmRequestWrapper) {
 
 405              * The request should be of type LCMRequestWrapper and the subrequestid should be 1
 
 407             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
 
 408             LcmRequest appcRequest = dmaapRequest.getBody();
 
 409             assertEquals(appcRequest.getCommonHeader().getSubRequestId(),"1");
 
 411             logger.debug("\n============ APPC received the request!!! ===========\n");
 
 414              * Simulate a success response from APPC and insert the response into the working memory
 
 416             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
 
 417             LcmResponse appcResponse = new LcmResponse(appcRequest);
 
 418             appcResponse.getStatus().setCode(400);
 
 419             appcResponse.getStatus().setMessage("AppC success");
 
 420             dmaapResponse.setBody(appcResponse);
 
 421             kieSession1.insert(dmaapResponse);
 
 422             kieSession2.insert(dmaapResponse);
 
 427      * This method will dump all the facts in the working memory.
 
 429      * @param kieSession the session containing the facts
 
 431     public void dumpFacts(KieSession kieSession) {
 
 432         logger.debug("Fact Count: {}", kieSession.getFactCount());
 
 433         for (FactHandle handle : kieSession.getFactHandles()) {
 
 434             logger.debug("FACT: {}", handle);
 
 439      * Test that SyntheticControlLoopOne blocks SyntheticControlLoopTwo
 
 440      * is enforced correctly.
 
 443     public void testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo() throws InterruptedException {
 
 444         logger.info("Beginning testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo");
 
 446          * Allows the PolicyEngine to callback to this object to
 
 447          * notify that there is an event ready to be pulled 
 
 450         for (TopicSink sink : noopTopics) {
 
 451             assertTrue(sink.start());
 
 456          * Create unique requestIds
 
 458         final UUID requestId1 = UUID.randomUUID();
 
 459         final UUID requestId2 = UUID.randomUUID();
 
 460         final UUID requestId3 = UUID.randomUUID();
 
 461         final UUID requestId4 = UUID.randomUUID();
 
 462         final UUID requestId5 = UUID.randomUUID();
 
 463         final String cl1 = controlLoopOneName.toString();
 
 464         final String cl2 = controlLoopTwoName.toString();
 
 465         final String t1 = "TARGET_1";
 
 466         final String t2 = "TARGET_2";
 
 468         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@"); 
 
 469         simulateOnset(requestId1, cl2, t1, kieSession2,"PERMIT");
 
 470         logger.info("@@@@@@@@@@ cl1 ONSET t1 @@@@@@@@@@"); 
 
 471         simulateOnset(requestId2, cl1, t1, kieSession1,"PERMIT");
 
 472         logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@"); 
 
 473         simulateAbatement(requestId1, cl2, t1, kieSession2);
 
 474         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Fail) @@@@@@@@@@"); 
 
 475         simulateOnset(requestId3, cl2, t1, kieSession2,"DENY");
 
 476         logger.info("@@@@@@@@@@ cl2 ONSET t2 (Success) @@@@@@@@@@");
 
 477         simulateOnset(requestId4, cl2, t2, kieSession2,"PERMIT");
 
 478         logger.info("@@@@@@@@@@ cl2 ABATED t2 @@@@@@@@@@"); 
 
 479         simulateAbatement(requestId4, cl2, t2, kieSession2);
 
 480         logger.info("@@@@@@@@@@ cl1 ABATED t1  @@@@@@@@@@"); 
 
 481         simulateAbatement(requestId2, cl1, t1, kieSession1);
 
 482         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@"); 
 
 483         simulateOnset(requestId5, cl2, t1, kieSession2,"PERMIT");
 
 484         logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@"); 
 
 485         simulateAbatement(requestId5, cl2, t1, kieSession2);
 
 488          * Print what's left in memory
 
 490         dumpFacts(kieSession1);
 
 491         dumpFacts(kieSession2);